diff --git a/lib/Components/loading_common.dart b/lib/Components/loading_common.dart index 8f1b63e..79acdd9 100644 --- a/lib/Components/loading_common.dart +++ b/lib/Components/loading_common.dart @@ -1,6 +1,11 @@ +import 'dart:io'; + import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; +import 'package:manager_api/api.dart'; +import 'package:path_provider/path_provider.dart'; import 'package:provider/provider.dart'; +import 'package:tablet_app/Components/cached_custom_resource.dart'; import 'package:tablet_app/Models/tabletContext.dart'; import 'package:tablet_app/app_context.dart'; import 'package:tablet_app/constants.dart'; @@ -54,11 +59,29 @@ class _LoadingCommonState extends State with TickerProviderStateM turns: Tween(begin: 0.0, end: 3.0).animate(_controller!), child: tabletAppContext.configuration != null && tabletAppContext.configuration!.loaderImageUrl != null ? //Image.network(tabletAppContext.configuration!.loaderImageUrl!) - CachedNetworkImage( - imageUrl: tabletAppContext.configuration!.loaderImageUrl!, - progressIndicatorBuilder: (context, url, downloadProgress) => - CircularProgressIndicator(value: downloadProgress.progress, color: primaryColor), - errorWidget: (context, url, error) => Icon(Icons.error), + // TODO Replace by CustomCacheResource.. + FutureBuilder( + future: _checkIfLocalResourceExists(tabletAppContext, tabletAppContext.configuration!.loaderImageId!), + builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + // Loader ou indicateur de chargement pendant la vérification + return CircularProgressIndicator(); + } else if (snapshot.hasError || snapshot.data == null) { + // Si la ressource locale n'existe pas ou s'il y a une erreur + print("not a local loader succck"); + return CachedNetworkImage( + imageUrl: tabletAppContext.configuration!.loaderImageUrl!, + progressIndicatorBuilder: (context, url, downloadProgress) => + CircularProgressIndicator(value: downloadProgress.progress, color: primaryColor), + errorWidget: (context, url, error) => Icon(Icons.error), + ); + } else { + print("Its a local loaaader yeah"); + return Image.file( + snapshot.data!, + ); + } + }, ) : Icon(Icons.museum_outlined, color: kTestSecondColor, size: size.height*0.1), ), @@ -67,4 +90,23 @@ class _LoadingCommonState extends State with TickerProviderStateM } } +Future _checkIfLocalResourceExists(TabletAppContext tabletAppContext, String resourceId) async { + try { + Directory? appDocumentsDirectory = await getDownloadsDirectory(); + String localPath = appDocumentsDirectory!.path; + Directory configurationDirectory = Directory('$localPath/${tabletAppContext.configuration!.id}'); + List fileList = configurationDirectory.listSync(); + + if(fileList.any((fileL) => fileL.uri.pathSegments.last.contains(resourceId))) { + File file = File(fileList.firstWhere((fileL) => fileL.uri.pathSegments.last.contains(resourceId)).path); + return file; + } + } catch(e) { + print("ERROR _checkIfLocalResourceExists CachedCustomResource"); + print(e); + } + + return null; +} + diff --git a/lib/Helpers/ImageCustomProvider.dart b/lib/Helpers/ImageCustomProvider.dart index 21e287a..e9b1be7 100644 --- a/lib/Helpers/ImageCustomProvider.dart +++ b/lib/Helpers/ImageCustomProvider.dart @@ -13,13 +13,12 @@ class ImageCustomProvider { Directory configurationDirectory = Directory('${tabletAppContext.localPath!}/${tabletAppContext.configuration!.id!}'); List fileList = configurationDirectory.listSync(); - print(fileList); - - if (fileList.isNotEmpty) { - File file = File(fileList.first.path); + if(fileList.any((fileL) => fileL.uri.pathSegments.last.contains(imageId))) { + File file = File(fileList.firstWhere((fileL) => fileL.uri.pathSegments.last.contains(imageId)).path); print("FILE EXISTT"); return FileImage(file); } + } } catch(e) { print("Error getImageProvider"); diff --git a/lib/Screens/MainView/main_view.dart b/lib/Screens/MainView/main_view.dart index 0c97ef8..2f6845f 100644 --- a/lib/Screens/MainView/main_view.dart +++ b/lib/Screens/MainView/main_view.dart @@ -51,6 +51,10 @@ class _MainViewWidget extends State { late Color backgroundColor; int rowCount = 4; + List? sectionsLocal; + bool isInit = true; // Use to make it faster and to load resource at init + bool isDialogOpen = false; + @override void initState() { final appContext = Provider.of(context, listen: false); @@ -58,6 +62,7 @@ class _MainViewWidget extends State { if(configurationDTO.isHour != null && configurationDTO.isHour!) { Timer.periodic(Duration(seconds: 1), (Timer t) => _getTime(currentHourDate)); } + print("Init state helloowww"); super.initState(); } @@ -295,8 +300,8 @@ class _MainViewWidget extends State { child: Container( height: kIsWeb ? size.height : size.height * 0.85, width: size.width * 0.9, - child: FutureBuilder( - future: getSections(appContext), + child: isInit ? FutureBuilder( + future: getSections(size, appContext), builder: (context, AsyncSnapshot snapshot) { if (snapshot.connectionState == ConnectionState.done) { if (snapshot.data == null) { @@ -304,102 +309,7 @@ class _MainViewWidget extends State { return Text(""); } else { - return Center( - child: GridView.builder( - shrinkWrap: true, - gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: rowCount), - itemCount: snapshot.data?.length, - itemBuilder: (BuildContext context, int index) { - return InkWell( - onTap: () { - setState(() { - sectionSelected = snapshot.data[index]; - }); - }, - child: Container( - decoration: boxDecoration(appContext, snapshot.data[index], false), - padding: const EdgeInsets.all(25), - margin: EdgeInsets.symmetric(vertical: 25, horizontal: 25), - child: Align( - alignment: Alignment.bottomRight, - child: FractionallySizedBox( - heightFactor: 0.4, - child: Container( - //color: Colors.green, - child: Column( - children: [ - Container( - //color: Colors.orange, - child: SizedBox( - width: double.infinity, - child: Align( - alignment: Alignment.centerRight, - child: HtmlWidget( - snapshot.data[index].title.firstWhere((translation) => translation.language == appContext.getContext().language).value, - customStylesBuilder: (element) { - return {'text-align': 'right'}; - }, - textStyle: TextStyle(fontSize: 25),//calculateFontSize(constraints.maxWidth, constraints.maxHeight, kIsWeb ? kWebMenuTitleDetailSize : kMenuTitleDetailSize)), - ), - ), - ), - ), - Container( - //color: Colors.red, - child: SizedBox( - width: double.infinity, - child: Align( - alignment: Alignment.centerRight, - child: HtmlWidget( - snapshot.data[index].description.firstWhere((translation) => translation.language == appContext.getContext().language).value, - customStylesBuilder: (element) { - return {'text-align': 'right'}; - }, - textStyle: TextStyle(fontSize: 20),//calculateFontSize(constraints.maxWidth, constraints.maxHeight, kIsWeb ? kWebMenuTitleDetailSize : kMenuTitleDetailSize)), - ), - ), - ), - ), - - /*Container( - color: Colors.orange, - child: FittedBox( - fit: BoxFit.fitWidth, - child: Align( - alignment: Alignment.centerRight, - child: HtmlWidget( - snapshot.data[index].title.firstWhere((translation) => translation.language == appContext.getContext().language).value, - customStylesBuilder: (element) { - return {'text-align': 'right'}; - }, - textStyle: new TextStyle(fontSize: calculateFontSize(context, kIsWeb ? kWebMenuTitleDetailSize: kMenuTitleDetailSize)), - ), - ), - ), - ), - FittedBox( - fit: BoxFit.fill, - child: Align( - alignment: Alignment.centerRight, - child: HtmlWidget( - snapshot.data[index].description.firstWhere((translation) => translation.language == appContext.getContext().language).value, - customStylesBuilder: (element) { - return {'text-align': 'right'}; - }, - textStyle: new TextStyle(fontSize: calculateFontSize(context, kIsWeb ? kWebMenuDescriptionDetailSize: kMenuDescriptionDetailSize), fontFamily: ""), - ), - ), - ),*/ - ], - ), - ) - ), - ), - ), - ); - } - ), - ); + return getGridSections(appContext); } } else if (snapshot.connectionState == ConnectionState.none) { return Text("No data"); @@ -411,7 +321,7 @@ class _MainViewWidget extends State { ); } } - ), + ) : getGridSections(appContext), ), ), if(configurationDTO.weatherCity != null) @@ -424,31 +334,6 @@ class _MainViewWidget extends State { )) ]), ), - floatingActionButton: InkWell( - onTap: () async { - var result = await showDialog( - builder: (BuildContext dialogContext) => AlertDialog( - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.all(Radius.circular(20.0)) - ), - content: Container( - width: size.width *0.5, - height: size.height *0.5, - child: DownloadConfigurationWidget(), - ), - actions: [], - ), context: context - ); - - print("RESULLLLT"); - print(result); - }, - child: Container( - width: 150, - height: 150, - color: Colors.red, - ), - ), ); } } @@ -488,28 +373,169 @@ class _MainViewWidget extends State { } } - Future?> getSections(dynamic appContext) async { + Future?> getSections(Size size, dynamic appContext) async { TabletAppContext tabletAppContext = await appContext.getContext(); - await getCurrentConfiguration(appContext); + print("getSectionsgetSectionsgetSectionsgetSections"); - try { - List? sections = await tabletAppContext.clientAPI!.sectionApi!.sectionGetFromConfiguration(tabletAppContext.configuration!.id!); - sections!.sort((a, b) => a.order!.compareTo(b.order!)); - return sections; - } catch (e) { - print(e); - print("IN CATCH"); - Navigator.pushAndRemoveUntil( - context, - MaterialPageRoute( - builder: (context) { - return ConfigViewWidget(); - }, - ), - (Route route) => false // For pushAndRemoveUntil + // DIALOG HERE + if(!isDialogOpen) { + isDialogOpen = true; + + var result = await showDialog( + builder: (BuildContext dialogContext) => AlertDialog( + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(20.0)) + ), + content: Container( + width: 400, + height: 200, + child: DownloadConfigurationWidget(), + ), + actions: [], + ), context: context + ); + print("COUCOUCOUCOU"); + print(result); + + isDialogOpen = false; + } else { + print("ALREADY OPEN LAAAA"); + } + + //await getCurrentConfiguration(appContext); + + print(sectionsLocal); + + if(isInit) { + try { + List? sections = await tabletAppContext.clientAPI!.sectionApi!.sectionGetFromConfiguration(tabletAppContext.configuration!.id!); + sections!.sort((a, b) => a.order!.compareTo(b.order!)); + sectionsLocal = sections; + isInit = false; + return sections; + } catch (e) { + print(e); + print("IN CATCH"); + Navigator.pushAndRemoveUntil( + context, + MaterialPageRoute( + builder: (context) { + return ConfigViewWidget(); + }, + ), + (Route route) => false // For pushAndRemoveUntil + ); + } + } + + return sectionsLocal; + } + + getGridSections(AppContext appContext) { + if(sectionsLocal != null) { + return Center( + child: GridView.builder( + shrinkWrap: true, + gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: rowCount), + itemCount: sectionsLocal!.length, + itemBuilder: (BuildContext context, int index) { + return InkWell( + onTap: () { + setState(() { + sectionSelected = sectionsLocal![index]; + }); + }, + child: Container( + decoration: boxDecoration(appContext, sectionsLocal![index], false), + padding: const EdgeInsets.all(25), + margin: EdgeInsets.symmetric(vertical: 25, horizontal: 25), + child: Align( + alignment: Alignment.bottomRight, + child: FractionallySizedBox( + heightFactor: 0.4, + child: Container( + //color: Colors.green, + child: Column( + children: [ + Container( + //color: Colors.orange, + child: SizedBox( + width: double.infinity, + child: Align( + alignment: Alignment.centerRight, + child: HtmlWidget( + sectionsLocal![index].title!.firstWhere((translation) => translation.language == appContext.getContext().language).value ?? "", + customStylesBuilder: (element) { + return {'text-align': 'right'}; + }, + textStyle: TextStyle(fontSize: 25),//calculateFontSize(constraints.maxWidth, constraints.maxHeight, kIsWeb ? kWebMenuTitleDetailSize : kMenuTitleDetailSize)), + ), + ), + ), + ), + Container( + //color: Colors.red, + child: SizedBox( + width: double.infinity, + child: Align( + alignment: Alignment.centerRight, + child: HtmlWidget( + sectionsLocal![index].description!.firstWhere((translation) => translation.language == appContext.getContext().language).value ?? "", + customStylesBuilder: (element) { + return {'text-align': 'right'}; + }, + textStyle: TextStyle(fontSize: 20),//calculateFontSize(constraints.maxWidth, constraints.maxHeight, kIsWeb ? kWebMenuTitleDetailSize : kMenuTitleDetailSize)), + ), + ), + ), + ), + + /*Container( + color: Colors.orange, + child: FittedBox( + fit: BoxFit.fitWidth, + child: Align( + alignment: Alignment.centerRight, + child: HtmlWidget( + snapshot.data[index].title.firstWhere((translation) => translation.language == appContext.getContext().language).value, + customStylesBuilder: (element) { + return {'text-align': 'right'}; + }, + textStyle: new TextStyle(fontSize: calculateFontSize(context, kIsWeb ? kWebMenuTitleDetailSize: kMenuTitleDetailSize)), + ), + ), + ), + ), + FittedBox( + fit: BoxFit.fill, + child: Align( + alignment: Alignment.centerRight, + child: HtmlWidget( + snapshot.data[index].description.firstWhere((translation) => translation.language == appContext.getContext().language).value, + customStylesBuilder: (element) { + return {'text-align': 'right'}; + }, + textStyle: new TextStyle(fontSize: calculateFontSize(context, kIsWeb ? kWebMenuDescriptionDetailSize: kMenuDescriptionDetailSize), fontFamily: ""), + ), + ), + ),*/ + ], + ), + ) + ), + ), + ), + ); + } + ), + ); + } else { + Center( + child: Text("Aucune section à afficher", style: TextStyle(fontSize: kNoneInfoOrIncorrect)), ); } + } } diff --git a/lib/Screens/PDF/pdf_view.dart b/lib/Screens/PDF/pdf_view.dart index 2c4130a..ac5335d 100644 --- a/lib/Screens/PDF/pdf_view.dart +++ b/lib/Screens/PDF/pdf_view.dart @@ -13,6 +13,7 @@ import 'package:provider/provider.dart'; import 'package:tablet_app/Components/loading_common.dart'; import 'package:tablet_app/Models/tabletContext.dart'; import 'package:tablet_app/app_context.dart'; +import 'package:tablet_app/constants.dart'; class PDFViewWidget extends StatefulWidget { @@ -160,7 +161,7 @@ class _PDFViewWidget extends State { } ), ) : - Center(child: Text("Le PDF ne peut pas être affiché, il n'existe pas")); + Center(child: Text("Le PDF ne peut pas être affiché, il n'existe pas", style: TextStyle(fontSize: kNoneInfoOrIncorrect))); } } //_webView diff --git a/lib/Screens/Puzzle/puzzle_view.dart b/lib/Screens/Puzzle/puzzle_view.dart index f5b2480..d2e9da4 100644 --- a/lib/Screens/Puzzle/puzzle_view.dart +++ b/lib/Screens/Puzzle/puzzle_view.dart @@ -10,6 +10,7 @@ import 'package:tablet_app/Components/loading_common.dart'; import 'package:tablet_app/Models/tabletContext.dart'; import 'package:tablet_app/Screens/Puzzle/message_dialog.dart'; import 'package:tablet_app/app_context.dart'; +import 'package:tablet_app/constants.dart'; import 'puzzle_piece.dart'; const IMAGE_PATH = 'image_path'; @@ -61,6 +62,10 @@ class _PuzzleView extends State { fit: BoxFit.fill, errorWidget: (context, url, error) => Icon(Icons.error), )); + } else { + setState(() { + isSplittingImage = false; + }); } }); @@ -204,8 +209,8 @@ class _PuzzleView extends State { key: _widgetKey, padding: const EdgeInsets.all(10.0), child: isSplittingImage ? Center(child: LoadingCommon()) : - puzzleDTO.image!.resourceUrl == null || realWidgetSize == null - ? Center(child: Text("Invalid image")) + puzzleDTO.image == null || puzzleDTO.image!.resourceUrl == null || realWidgetSize == null + ? Center(child: Text("Aucune image à afficher", style: TextStyle(fontSize: kNoneInfoOrIncorrect))) : Center( child: Padding( padding: const EdgeInsets.all(8.0), diff --git a/lib/Screens/Slider/slider_view.dart b/lib/Screens/Slider/slider_view.dart index c7a9fe2..b0d4ca6 100644 --- a/lib/Screens/Slider/slider_view.dart +++ b/lib/Screens/Slider/slider_view.dart @@ -221,7 +221,7 @@ class _SliderView extends State { ), ), if(sliderDTO.contents == null || sliderDTO.contents!.length == 0) - Center(child: Text("Aucun contenu à afficher", style: TextStyle(fontSize: kNoneInfoOrIncorrect),)) + Center(child: Text("Aucun contenu à afficher", style: TextStyle(fontSize: kNoneInfoOrIncorrect))) // Description /*Container( height: sliderDTO.images != null && sliderDTO.images.length > 0 ? size.height *0.3 : size.height *0.6, diff --git a/lib/Screens/Web/web_view.dart b/lib/Screens/Web/web_view.dart index 653387e..1bbbf09 100644 --- a/lib/Screens/Web/web_view.dart +++ b/lib/Screens/Web/web_view.dart @@ -5,6 +5,7 @@ import 'dart:ui' as ui; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:manager_api/api.dart'; +import 'package:tablet_app/constants.dart'; import 'package:webview_flutter/webview_flutter.dart'; import 'package:webview_flutter_platform_interface/webview_flutter_platform_interface.dart'; //import 'package:webview_flutter_web/webview_flutter_web.dart'; @@ -30,6 +31,7 @@ class _WebView extends State { webDTO = WebDTO.fromJson(jsonDecode(widget.section!.data!))!; print(webDTO); + if(kIsWeb) { /*_iframeElement.src = webDTO.source_!; _iframeElement.style.border = 'none'; @@ -40,30 +42,37 @@ class _WebView extends State { (int viewId) => _iframeElement, );*/ } else { - controller = WebViewController() - ..setJavaScriptMode(JavaScriptMode.unrestricted) - ..setBackgroundColor(const Color(0x00000000)) - ..setNavigationDelegate( - NavigationDelegate( - onProgress: (int progress) { - // Update loading bar. - }, - onPageStarted: (String url) {}, - onPageFinished: (String url) {}, - onWebResourceError: (WebResourceError error) {}, - onNavigationRequest: (NavigationRequest request) { - Uri sourceUri = Uri.parse(webDTO.source_!); - Uri requestUri = Uri.parse(request.url); - if (requestUri.host != sourceUri.host) { // handle navigation to site - print('blocking navigation to $request}'); - return NavigationDecision.prevent; - } - return NavigationDecision.navigate; - }, - ), - ) - ..loadRequest(Uri.parse(webDTO.source_!)); + if(webDTO.source_ != null && webDTO.source_!.length > 0) { + try { + controller = WebViewController() + ..setJavaScriptMode(JavaScriptMode.unrestricted) + ..setBackgroundColor(const Color(0x00000000)) + ..setNavigationDelegate( + NavigationDelegate( + onProgress: (int progress) { + // Update loading bar. + }, + onPageStarted: (String url) {}, + onPageFinished: (String url) {}, + onWebResourceError: (WebResourceError error) {}, + onNavigationRequest: (NavigationRequest request) { + Uri sourceUri = Uri.parse(webDTO.source_!); + Uri requestUri = Uri.parse(request.url); + + if (requestUri.host != sourceUri.host) { // handle navigation to site + print('blocking navigation to $request}'); + return NavigationDecision.prevent; + } + return NavigationDecision.navigate; + }, + ), + ) + ..loadRequest(Uri.parse(webDTO.source_!)); + } catch (e) { + print("Invalid source ${webDTO.source_}"); + } + } } super.initState(); @@ -98,5 +107,5 @@ class _WebView extends State { viewType: webDTO.source_!, ) : WebViewWidget(controller: controller!) : - Center(child: Text("La page internet ne peut pas être affichée, l'url est incorrecte ou vide")); + Center(child: Text("La page internet ne peut pas être affichée, l'url est incorrecte ou vide", style: new TextStyle(fontSize: kNoneInfoOrIncorrect))); } //_webView \ No newline at end of file diff --git a/lib/Services/downloadService.dart b/lib/Services/downloadService.dart index 49d5737..9def30c 100644 --- a/lib/Services/downloadService.dart +++ b/lib/Services/downloadService.dart @@ -10,6 +10,7 @@ import 'package:flutter/foundation.dart'; import 'package:http/http.dart' as http; import 'package:path_provider/path_provider.dart'; import 'package:permission_handler/permission_handler.dart'; +import 'package:tablet_app/constants.dart'; class DownloadConfigurationWidget extends StatefulWidget { DownloadConfigurationWidget(); @@ -19,126 +20,101 @@ class DownloadConfigurationWidget extends StatefulWidget { } class _DownloadConfigurationWidgetState extends State { - int? nbrResources; ValueNotifier currentResourceIndex = ValueNotifier(0); - - @override - void initState() { - super.initState(); - } - - @override - void dispose() { - super.dispose(); - } + ValueNotifier currentResourceNbr = ValueNotifier(-1); + bool isAlreadyDownloading = false; Future download(BuildContext buildContext, TabletAppContext tabletAppContext) async { bool isAllLanguages = true; - ExportConfigurationDTO? exportConfigurationDTO; - try{ - print(tabletAppContext.configuration!.id!); - print("essai"); + if(!isAlreadyDownloading) { + isAlreadyDownloading = true; - // Retrieve all url from resource to download (get all resource from configuration en somme) - exportConfigurationDTO = await tabletAppContext.clientAPI!.configurationApi!.configurationExport(tabletAppContext.configuration!.id!); - } catch(e) { - print("Erreur lors du téléchargement de la configuration et de ses ressources !"); - print(e); - return false; - } + ExportConfigurationDTO? exportConfigurationDTO; + try{ + // Retrieve all url from resource to download (get all resource from configuration en somme) + exportConfigurationDTO = await tabletAppContext.clientAPI!.configurationApi!.configurationExport(tabletAppContext.configuration!.id!); + } catch(e) { + print("Erreur lors du téléchargement de la configuration et de ses ressources !"); + print(e); + return false; + } - print("COUCUO heeere"); - print(exportConfigurationDTO); - print(exportConfigurationDTO.resources!.length); + exportConfigurationDTO.resources!.forEach((element) { + print(element.id); + print(element.label); + }); - exportConfigurationDTO.resources!.forEach((element) { - print(element.id); - print(element.label); - }); + if(exportConfigurationDTO.resources != null && exportConfigurationDTO.resources!.isNotEmpty) { + Map statuses = await [ + Permission.storage, + ].request(); + if(statuses[Permission.storage] == PermissionStatus.granted) { + try{ + try { + Directory directory = Directory('${tabletAppContext.localPath}'); + List allConfigurations = directory.listSync(); + Directory configurationDirectory = Directory('${tabletAppContext.localPath}/${tabletAppContext.configuration!.id}'); + if(!allConfigurations.any((configurationDirectory) => configurationDirectory.uri.pathSegments.any((element) => element == tabletAppContext.configuration!.id))) { + // create directory + print("Trying to create directory"); + configurationDirectory.createSync(recursive: true); + print('Répertoire créé avec succès.'); + } + } catch(e) { + print("Listing failed, so try to create directory"); + Directory configurationDirectory = Directory('${tabletAppContext.localPath}/${tabletAppContext.configuration!.id}'); - if(exportConfigurationDTO != null && exportConfigurationDTO.resources != null && exportConfigurationDTO.resources!.isNotEmpty) { - nbrResources = exportConfigurationDTO.resources!.where((resource) => resource.type != ResourceType.ImageUrl && resource.type != ResourceType.VideoUrl && resource.url != null).length; - - print("i'm here"); - print(nbrResources); - Directory? appDocumentsDirectory = await getDownloadsDirectory(); - String localPath = appDocumentsDirectory!.path; - - print(localPath); - - Map statuses = await [ - Permission.storage, - ].request(); - - print(statuses[Permission.storage]); - print(statuses); - - if(statuses[Permission.storage] == PermissionStatus.granted) { - - try{ - try { - Directory directory = Directory('$localPath'); - List allConfigurations = directory.listSync(); - print("LISTING DONE"); - - Directory configurationDirectory = Directory('$localPath/${tabletAppContext.configuration!.id}'); - print("configurationDirectory TEST BEFORE"); - if(!allConfigurations.any((configurationDirectory) => configurationDirectory.uri.pathSegments.any((element) => element == tabletAppContext.configuration!.id))) { - // create directory - print("Trying to create directory"); configurationDirectory.createSync(recursive: true); print('Répertoire créé avec succès.'); - } else { - print('EXISTE D2J0 NIGAUD.'); + } + + Directory configurationDirectory = Directory('${tabletAppContext.localPath}/${tabletAppContext.configuration!.id}'); + List fileList = configurationDirectory.listSync(); + + for (var file in fileList) { + print(file.uri.pathSegments.last); + } + + var resourcesToDownload = exportConfigurationDTO.resources!.where((resource) => resource.type != ResourceType.ImageUrl && resource.type != ResourceType.VideoUrl && resource.type != ResourceType.JsonUrl && resource.url != null && !fileList.any((fileL) => fileL.uri.pathSegments.last.contains(resource.id!))); + + currentResourceNbr.value = resourcesToDownload.length; + + // foreach ou on va tout télécharger - avec un joli etape 0 / length - on peut rendre tout lent on s'en fou ça ne ce fait qu'une fois + for (var resource in resourcesToDownload) { + bool success = await downloadResource(tabletAppContext, resource, tabletAppContext.localPath!); + + if (success) { + currentResourceIndex.value++; + } else { + print("NOT SUCCESSS"); + } + } + + // Delete others that are no more used + var resourceToDelete = fileList.where((fileL) => + !exportConfigurationDTO!.resources!.any((resource) => + resource.id != null && fileL.uri.pathSegments.last.contains(resource.id!))); + + for (var resource in resourceToDelete) { + print("resource to DELETE"); + print(resource.path); + // resource.deleteSync(); + // Preserve call to firebase // TODO uncomment if needed } } catch(e) { - print("Listing failed, so try to create directory"); - Directory configurationDirectory = Directory('$localPath/${tabletAppContext.configuration!.id}'); - - configurationDirectory.createSync(recursive: true); - print('Répertoire créé avec succès.'); + print("ERRORRRR"); + print(e); + return false; } - - print('Now its time to try listing filesin created directory'); - Directory configurationDirectory = Directory('$localPath/${tabletAppContext.configuration!.id}'); - List fileList = configurationDirectory.listSync(); - - print("HERE LIST in directory"); - - for (var file in fileList) { - print(file.uri.pathSegments.last); - } - - // foreach ou on va tout télécharger - avec un joli etape 0 / length - on peut rendre tout lent on s'en fou ça ne ce fait qu'une fois - exportConfigurationDTO.resources!.forEach((resource) async { - - if(fileList.any((fileL) => fileL.uri.pathSegments.last.contains(resource.id!))) { - print("Already exist TRIPLE NIGAUD!"); - currentResourceIndex.value++; - } else { - if(resource.type != ResourceType.ImageUrl && resource.type != ResourceType.VideoUrl && resource.type != ResourceType.JsonUrl && resource.url != null) { - bool success = await downloadResource(tabletAppContext, resource, localPath); - - if (success) { - currentResourceIndex.value++; - } - } - } - }); - } catch(e) { - print("ERRORRRR"); - print(e); + } else { return false; } - } else { - return false; } } - // Puis après faudra changer tous les appels à une resourceUrl avec un get local de la resource return true; } @@ -149,26 +125,53 @@ class _DownloadConfigurationWidgetState extends State( - valueListenable: currentResourceIndex, - builder: (context, value, _) { - return Center( - child: Text( - value.toString()+'/'+nbrResources.toString(), - style: TextStyle(fontSize: 15, fontWeight: FontWeight.w500), - ), + valueListenable: currentResourceNbr, + builder: (context, valueNbr, _) { + return ValueListenableBuilder( + valueListenable: currentResourceIndex, + builder: (context, valueIndex, _) { + return valueNbr != -1 && valueNbr != 0 ? Center( + child: Padding( + padding: const EdgeInsets.only(bottom: 8.0), + child: Text( + "${valueIndex.toString()}/${valueNbr.toString()}", + style: TextStyle(fontSize: 45, fontWeight: FontWeight.w500), + ), + ), + ) : SizedBox(height: 0,width: 0); + } ); } ), + FutureBuilder(future: download(context, tabletAppContext), builder: (context, snapshot) { + if (snapshot.connectionState == ConnectionState.waiting) { + // Loader ou indicateur de chargement pendant la vérification + Color primaryColor = tabletAppContext.configuration!.primaryColor != null ? new Color(int.parse(tabletAppContext.configuration!.primaryColor!.split('(0x')[1].split(')')[0], radix: 16)) : kTestSecondColor; + return Center(child: CircularProgressIndicator(color: primaryColor)); + } else { + return ValueListenableBuilder( + valueListenable: currentResourceNbr, + builder: (context, valueNbr, _) { + return ValueListenableBuilder( + valueListenable: currentResourceIndex, + builder: (context, valueIndex, _) { + return Center( + child: Text( + valueIndex == valueNbr && valueNbr != -1 ? valueNbr == 0 ? "Tout est à jour" : "Mise à jour finie" : "Mise à jour en cours", + style: TextStyle(fontSize: 25), + ), + ); + } + ); + } + ); + } + }), + Spacer() ], ); }