import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import 'dart:ui'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:connectivity/connectivity.dart'; import 'package:flutter_cache_manager/flutter_cache_manager.dart'; import 'package:flutter_upchunk/flutter_upchunk.dart'; import 'package:path_provider/path_provider.dart'; import 'package:share_plus/share_plus.dart'; import 'package:tapioca/tapioca.dart'; import 'package:teso/Classes/API%20Clasess/PostUpload.dart'; import 'package:teso/Classes/Connection.dart'; import 'package:teso/Classes/Firebase/Posts.dart'; import 'package:teso/Classes/ReportedContent.dart'; import 'package:teso/Classes/Uploading.dart'; import 'package:teso/Pages/Sub_Pages/@Generic/SuccessRedeem.dart'; import 'package:teso/Pages/Sub_Pages/@Generic/ErrorRedeem.dart'; import 'package:teso/Classes/API%20Clasess/CommentsPost.dart'; import 'package:teso/Classes/API%20Clasess/CouponDetails.dart'; import 'package:teso/Classes/API%20Clasess/Post.dart'; import 'package:teso/Classes/API%20Clasess/PostFav.dart'; import 'package:teso/providers/pageAnimations.dart'; import 'package:teso/util/SizeConfig.dart'; import 'package:teso/util/consts.dart'; import 'package:http/http.dart' as http; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:teso/Classes/TesoUser.dart'; import 'package:teso/Classes/API Clasess/UserFavCategory.dart'; import 'package:teso/Classes/API Clasess/CouponHead.dart'; import 'package:teso/Notifications/NotificationPlugin.dart'; import 'package:teso/Classes/Payload.dart'; class UserProvider extends ChangeNotifier { UserProvider() { getCurrentUser(); } TesoUser currentUser; List interest = []; List posts = []; List friends = []; List mycoupons = []; List pending = []; List uploadOperation = []; bool wifi = false; bool firstTime = true; bool saving = false; List blockedContent = []; List blockedUsers = []; List blockUserList = []; void updateUser(user) async { currentUser = await update(user); SharedPreferences.getInstance().then((prefs) { prefs.setString("currentUser", currentUser.toString()); }); notifyListeners(); } void setUser(user) { currentUser = user; SharedPreferences.getInstance().then((prefs) { prefs.setString("currentUser", currentUser.toString()); }); notifyListeners(); } getPending() { return pending; } getCurrentUser() async { String currentSaveUser; SharedPreferences.getInstance().then((prefs) async { currentSaveUser = prefs.getString("currentUser"); if (currentSaveUser == null) { } else { Map user = jsonDecode(currentSaveUser) as Map; TesoUser olduser = TesoUser.fromJSON(user); currentUser = olduser; prefs.setString("currentUser", currentUser.toString()); } }); Future.delayed(Duration(seconds: 5), () => notifyListeners()); return currentUser; } setFavs(List categories) { interest = categories; SharedPreferences.getInstance().then((prefs) { prefs.setStringList("favoriteCats", categories); }); notifyListeners(); } getFavs() async { try { await pullFavoriteCategories(); } catch (e) { SharedPreferences.getInstance().then((prefs) { interest = prefs.getStringList("favoriteCats"); if (interest != null) if (interest.isEmpty) { interest = []; } }); } } Future update(TesoUser user) async { SharedPreferences prefs = await SharedPreferences.getInstance(); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': prefs.getString('tokensTeso') }; var register2 = serverLocation + 'users/updateUser'; var client1 = await http.post(Uri.parse(register2), body: json.encode(user), headers: requestHeaders); if (client1.statusCode == 200) { Map handler = jsonDecode(client1.body); TesoUser tokenHandler = TesoUser.fromJSON(handler); return tokenHandler; } else { return null; } } Future> pullFavoriteCategories() async { SharedPreferences prefs = await SharedPreferences.getInstance(); List favs; Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': prefs.getString('tokensTeso') }; var register2 = serverLocation + 'favoriteCategories/pullUser'; var client1 = await http.post(Uri.parse(register2), body: json.encode(prefs.getString("id")), headers: requestHeaders); if (client1.statusCode == 200) { var handler = jsonDecode(client1.body); favs = List.from( handler.map((model) => UserFavCategory.fromJSON(model)).toList()); setFavs(favs.map((e) => e.categoryCode).toList()); return interest = favs.map((e) => e.categoryCode).toList(); } else { return null; } } updateFavoriteCategories(List catF) async { SharedPreferences prefs = await SharedPreferences.getInstance(); String id = prefs.getString("id"); List favs = []; catF.forEach((element) async { UserFavCategory category = new UserFavCategory(); category.userGuid = id; category.categoryCode = element; category.countID = DateTime.now().toString() + id; favs.add(category); }); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': prefs.getString('tokensTeso') }; var register2 = serverLocation + 'favoriteCategories/updateFavorites'; var client1 = await http.post(Uri.parse(register2), body: json.encode(favs), headers: requestHeaders); if (client1.statusCode == 200) { setFavs(catF); } else { return null; } } Future getMonthlyStatus() async { SharedPreferences prefs = await SharedPreferences.getInstance(); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': prefs.getString('tokensTeso') }; try { var register2 = serverLocation + 'monthly-desires/check-status'; var client1 = await http.get(Uri.parse(register2), headers: requestHeaders); if (client1.statusCode == 200) { if (client1.body == "not submitted") { Payload payload = new Payload(); payload.loadID = "TESN002"; payload.load1 = "DesireComeTrue"; await notificationPlugin.showNotification( "Desire Come True", "You haven't set up your Desire Come True list for next month", payload.toString(), ); } } } catch (e) { print(e); } } void updatePosted(FBPosts postNow) { posts.add(postNow); notifyListeners(); // predownloadAds(posts.map((e) => e.playbackID).toList()); } Future pullAds() async { SharedPreferences.getInstance().then((prefs) async { String id = prefs.getString("id"); FirebaseFirestore.instance .collection("posts") .where("publisher", isEqualTo: id) .snapshots() .listen((snap) async { this.posts = snap.docs.map((e) => FBPosts.fromJSON(e.data())).toList(); if (this.posts != null) this.posts.sort((b, a) => a.timestamp.compareTo(b.timestamp)); }); notifyListeners(); }); //predownloadAds(this.posts.map((e) => e.playbackID).toList()); } Future commentPost(CommentsPost comment) async { SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso"); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; var register = serverLocation + 'posts/add-comment'; var client = await http.post(Uri.parse(register), body: json.encode(comment), headers: requestHeaders); if (client.statusCode == 200) { print(client.body); } } void unCommentPost(CommentsPost comment) async { SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso"); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; var register = serverLocation + 'posts/delete-comment'; var client = await http.post(Uri.parse(register), body: json.encode(comment), headers: requestHeaders); if (client.statusCode == 200) { print(client.body); } } void addLike(PostFav like) async { try { SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso"); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; var register = serverLocation + 'posts/add-like'; var client = await http.post(Uri.parse(register), body: json.encode(like), headers: requestHeaders); if (client.statusCode == 200) { print(client.body); } } catch (e) { print(e.toString()); } } void deleteLike(String like) async { try { SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso"); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; var register = serverLocation + 'posts/remove-like'; var client = await http.post(Uri.parse(register), body: json.encode(like), headers: requestHeaders); if (client.statusCode == 200) { print(client.body); } } catch (e) { print(e); } } void deletePost(Post post) async { try { SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso"); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; Map muxHeaders = {'Authorization': token}; var register = serverLocation + 'posts/delete-post'; var client = await http.post(Uri.parse(register), body: json.encode(post), headers: requestHeaders); print(client.body); if (client.statusCode == 200) { http.get( Uri.parse( tesoStreaming + "api/mobile/upload/delete/" + post.playbackID), headers: muxHeaders); this.posts.removeWhere((element) => element.postID == post.postID); notifyListeners(); } } catch (e) { print(e); } } void viewPost(Post post) async { try { SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso"); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; var register = serverLocation + 'posts/view-post'; await http.post(Uri.parse(register), body: json.encode(post.postID), headers: requestHeaders); } catch (e) { print(e); } } // coupons Future viewCoupon(CouponsHead coupon) async { SharedPreferences prefs = await SharedPreferences.getInstance(); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': prefs.getString('tokensTeso') }; try { var register2 = serverLocation + 'coupons/viewCoupon'; var client1 = await http.post(Uri.parse(register2), body: json.encode(coupon), headers: requestHeaders); if (client1.statusCode == 200) { return 200; } else { return 400; } } catch (e) { return 400; } } Future loadFriends() async { SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso"); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; var register = serverLocation + 'relationships/friends'; var client = await http.get(Uri.parse(register), headers: requestHeaders); if (client.statusCode == 200) { var people = jsonDecode(client.body); friends = List.from( people.map((model) => TesoUser.fromJSON(model)).toList()); notifyListeners(); } } Future getUserInformation() async { SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso"); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; var register = serverLocation + 'user_details/pullInformation'; var client = await http.get(Uri.parse(register), headers: requestHeaders); if (client.statusCode == 200) { var people = jsonDecode(client.body); TesoUser user = TesoUser.fromJSON(people); setUser(user); } } Future getCoupons() async { SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso"); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; var register = serverLocation + 'coupons/acquiredcoupons'; var client = await http.get(Uri.parse(register), headers: requestHeaders); if (client.statusCode == 200) { var details = jsonDecode(client.body); mycoupons = List.from( details.map((model) => CouponDetails.fromJSON(model)).toList()); notifyListeners(); } } Future redeemCoupon(CouponDetails coupon, context) async { SharedPreferences prefs = await SharedPreferences.getInstance(); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': prefs.getString('tokensTeso') }; try { var register2 = serverLocation + 'coupons/redeemCoupon'; var client1 = await http.post(Uri.parse(register2), body: json.encode(coupon), headers: requestHeaders); print(client1.body); if (client1.statusCode == 200) { var data = client1.body; int coins = int.tryParse(data); Payload payload = new Payload(); payload.loadID = "TESN003"; payload.load1 = "CouponRedemption"; await notificationPlugin.showNotification( "Coupon Redeem", "You have successfully redeem a " + coupon.issuer.businessName + " " + coupon.type + " coupon", payload.toString(), ); getCoupons(); await Navigator.pushReplacement( context, PageTransition( child: SuccessfullyRedeemed( couponDetails: coupon, returns: coins, ), type: PageTransitionType.fade, ), ); Navigator.pop(context); } else { Navigator.pushReplacement( context, PageTransition( child: ErrorRedeem(), type: PageTransitionType.fade, ), ); } } catch (e) { print(e); Navigator.pushReplacement( context, PageTransition( child: ErrorRedeem(), type: PageTransitionType.fade, ), ); } } predownloadAds(List paths) { try { // if (wifi) // paths.forEach((path) async { // final fileInfo = await DefaultCacheManager() // .getFileFromCache(tesoStreaming + path); // if (fileInfo == null || fileInfo.file == null) { // unawaited(DefaultCacheManager() // .downloadFile(tesoStreaming + "pd/" + path)); // } // }); } catch (e) { print(e); } } Future uploadPost(Uploading uploads) async { try { Payload payload = new Payload(); payload.loadID = "TESN003"; payload.load1 = "Posted"; SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso"); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; Map muxHeaders = {'Authorization': token}; var uploadOptions = UpChunkOptions() ..endPoint = uploads.muxuploadURL ..file = File(uploads.path) ..onProgress = (progress) { print('Upload progress: ${progress.ceil()}%'); pending.forEach((element) { if (element.id == uploads.id) { uploads.pending = progress.ceil() / 100; uploads.isProcessing = false; } }); notifyListeners(); } ..onError = (String message, int chunk, int attempts) { print('UpChunk error 💥 🙀:'); print(' - Message: $message'); print(' - Chunk: $chunk'); print(' - Attempts: $attempts'); pending.removeWhere((element) => element.id == uploads.id); notifyListeners(); } ..onSuccess = () async { var client1 = await http.get( Uri.parse( "${tesoStreaming}api/mobile/upload/playback/${uploads.muxuploadID}"), headers: muxHeaders); print('Upload complete! 👋'); if (client1.statusCode == 200) { var details = jsonDecode(client1.body); var details1 = details[0]; var data = details1["0"]; PostUpload videoUpload = new PostUpload(); videoUpload.aspect = uploads.aspect; videoUpload.campaignID = uploads.campaignID; videoUpload.title = uploads.title; videoUpload.path = data["data"]["id"]; videoUpload.thumbnail = details1["asset_id"]; var register2 = serverLocation + "posts/upload-post"; var client2 = await http.post(Uri.parse(register2), body: json.encode(videoUpload), headers: requestHeaders); if (client2.statusCode == 200) { pending.removeWhere((element) => element.id == uploads.id); notifyListeners(); } else { pending.removeWhere((element) => element.id == uploads.id); notifyListeners(); } } else { pending.removeWhere((element) => element.id == uploads.id); // print(e); notifyListeners(); } }; var uploadChunk = UpChunk.createUpload(uploadOptions); uploads.token = uploadChunk; pending.add(uploads); notifyListeners(); } catch (e) { pending.removeWhere((element) => element.id == uploads.id); print(e); } } Future cancelUpload(Uploading uploads) async { try { // uploader.cancel(taskId: uploads.id); uploads.token.stop(); pending.remove(uploads); notifyListeners(); } catch (e) { print(e); } } connectionToServer(context) { MyConnectivity _connectivity = MyConnectivity.instance; _connectivity.initialise(); _connectivity.myStream.listen((source) { if (source.keys.toList()[0] == ConnectivityResult.wifi && source.values.toList()[0]) { final snackBar = SnackBar( content: Text( 'Connected', textAlign: TextAlign.center, style: TextStyle(color: Colors.white), ), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), backgroundColor: Colors.green, duration: Duration( seconds: 3, ), ); if (!firstTime) ScaffoldMessenger.of(context).showSnackBar(snackBar); firstTime = false; wifi = true; notifyListeners(); } else if (source.keys.toList()[0] == ConnectivityResult.mobile && source.values.toList()[0]) { final snackBar = SnackBar( content: Text( 'Connected', textAlign: TextAlign.center, style: TextStyle(color: Colors.white), ), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), backgroundColor: Colors.green, duration: Duration( seconds: 3, ), ); if (!firstTime) ScaffoldMessenger.of(context).showSnackBar(snackBar); firstTime = false; wifi = false; notifyListeners(); } else { final snackBar = SnackBar( content: Text( 'No Internet Connection Available', textAlign: TextAlign.center, style: TextStyle(color: Colors.white), ), action: SnackBarAction( label: 'Retry', textColor: Colors.white, onPressed: () => connectionToServer(context), ), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), backgroundColor: Colors.red, duration: Duration( seconds: 3, ), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); firstTime = false; wifi = false; notifyListeners(); } }); } Future downloadVideo(String postID, String playbackID, String rendition, Uint8List imageBitmap, context) async { if (!saving) { saving = true; final snackBar = SnackBar( content: Text( "Processing", textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: SizeConfig.blockSizeHorizontal * 3.5), ), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), backgroundColor: Color.fromRGBO(0, 0, 0, 0.5), duration: Duration( seconds: 3, ), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); try { if (rendition == null) { SharedPreferences prefs = await SharedPreferences.getInstance(); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': prefs.getString('tokensTeso') }; var register2 = serverLocation + 'posts/getrendition'; var client1 = await http .post(Uri.parse(register2), body: json.encode(postID), headers: requestHeaders) .timeout( Duration( seconds: 5, ), ); if (client1.statusCode == 200) { rendition = client1.body; } else { saving = false; final snackBar = SnackBar( content: Text( "An error occurred while saving ad try again", textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: SizeConfig.blockSizeHorizontal * 3.5), ), behavior: SnackBarBehavior.floating, margin: EdgeInsets.only( left: 10, right: 10, bottom: MediaQuery.of(context).size.height * 0.80), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), backgroundColor: Color(0XFF800000), duration: Duration( seconds: 2, ), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); } } var fileInfo = await DefaultCacheManager() .getSingleFile(tesoStreamMux + playbackID + "/$rendition?download"); String location = await getTemporaryDirectory().then((value) => value.path + "/" + DateTime.now().millisecondsSinceEpoch.toString() + ".mp4"); final tapiocaBalls = [ TapiocaBall.imageOverlay(imageBitmap, 0, 50), ]; final cup = Cup(Content(fileInfo.path), tapiocaBalls); await cup.suckUp(location); Share.shareFiles([location]); } catch (e) { saving = false; final snackBar = SnackBar( content: Text( "An error occurred while saving ad try again", textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: SizeConfig.blockSizeHorizontal * 3.5), ), behavior: SnackBarBehavior.floating, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), backgroundColor: Color(0XFF800000), duration: Duration( seconds: 3, ), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); } saving = false; } else { final snackBar = SnackBar( content: Text( "Try sharing after saving is complete", textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: SizeConfig.blockSizeHorizontal * 3.5), ), behavior: SnackBarBehavior.floating, margin: EdgeInsets.only(bottom: MediaQuery.of(context).size.height * 0.80), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), backgroundColor: Colors.grey[800], duration: Duration( seconds: 5, ), ); ScaffoldMessenger.of(context).showSnackBar(snackBar); } notifyListeners(); } checkRelationship(String id) { return friends.any((element) => element.userGUID == id); } Future flagPost(Post post, int reportID) async { try { SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso"); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; ReportedContent report = new ReportedContent(); report.postID = post.postID; report.publisherID = post.publisherID; report.report = reportID; var register = serverLocation + 'posts/flag-post'; var client = await http.post(Uri.parse(register), body: json.encode(report), headers: requestHeaders); if (client.statusCode == 200) { blockedContent.add(post.postID); notifyListeners(); } } catch (_) {} } checkBlockedUsers() async { try { SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso"); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; var register = serverLocation + 'users/blocked-users'; var client = await http.get(Uri.parse(register), headers: requestHeaders); if (client.statusCode == 200) { var people = jsonDecode(client.body); blockUserList = List.from( people.map((model) => TesoUser.fromJSON(model)).toList()); blockedUsers = blockUserList.map((b) => b.userGUID).toList(); } notifyListeners(); } catch (e) { print(e); } } checkBlockedContent() async {} Future blockUser(TesoUser user) async { try { SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso"); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; var register = serverLocation + 'relationships/block'; var client = await http.post(Uri.parse(register), body: json.encode(user.userGUID), headers: requestHeaders); if (client.statusCode == 200) { blockedUsers.add(user.userGUID); blockUserList.add(user); notifyListeners(); } } catch (_) {} } Future unblockUser(TesoUser user) async { try { SharedPreferences prefs = await SharedPreferences.getInstance(); String token = prefs.getString("tokensTeso"); Map requestHeaders = { 'Content-type': 'application/json', 'Authorization': token }; var register = serverLocation + 'relationships/unblock'; var client = await http.post(Uri.parse(register), body: json.encode(user.userGUID), headers: requestHeaders); if (client.statusCode == 200) { blockedUsers.remove(user.userGUID); blockUserList.remove(user); notifyListeners(); } } catch (_) {} } }