Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main' into 159-afficher-les-chat…
Browse files Browse the repository at this point in the history
…s-du-diététicien
  • Loading branch information
LucaCoduriV committed Sep 5, 2022
2 parents 5eb2a09 + 523a955 commit 12e88ba
Show file tree
Hide file tree
Showing 16 changed files with 176 additions and 49 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/continuousDeployment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ jobs:
- name: Setup Flutter
uses: subosito/flutter-action@v1
with:
flutter-version: "3.0.5"
flutter-version: "3.3.0"

- name: Pub Get Packages
run: flutter pub get
Expand Down
7 changes: 7 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@
"request": "launch",
"flutterMode": "debug",
"program": "lib/scripts/test_email.dart"
},
{
"name": "App run",
"type": "dart",
"request": "launch",
"flutterMode": "debug",
"program": "lib/scripts/app_run.dart"
}
]
}
71 changes: 34 additions & 37 deletions lib/api/firebase_document.dart
Original file line number Diff line number Diff line change
@@ -1,56 +1,53 @@
import 'dart:developer';
import 'dart:io';
import 'package:flutter/widgets.dart';
import 'dart:typed_data';
import 'package:pdg_app/api/ifile.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:uuid/uuid.dart';

/// Implementation of [IFile] for firebase storage.
class FirebaseFile implements IFile {
final bucket = FirebaseStorage.instance;

/// Maximum file download size in bytes.
static const maxFileSize = 20 * 1024 * 1024; // 20 MB

late final FirebaseStorage bucket;
late final storageRef = bucket.ref();

@override
Future<void> uploadFile(File file, int type) async {
String filePath = (type == 0) ? 'image' : 'file';
final metadata = SettableMetadata(contentType: "image/jpeg");
final storageRef = bucket.ref();
final uploadTask = storageRef.child(filePath).putFile(file, metadata);
FirebaseFile(this.bucket);

uploadTask.snapshotEvents.listen((TaskSnapshot taskSnapshot) {
switch (taskSnapshot.state) {
case TaskState.running:
final progress =
100.0 * (taskSnapshot.bytesTransferred / taskSnapshot.totalBytes);
log("Upload is $progress% complete.");
break;
case TaskState.paused:
log("Upload is paused.");
break;
case TaskState.canceled:
log("Upload was canceled");
break;
case TaskState.error:
ErrorDescription(" unsuccessful uploads");
break;
case TaskState.success:
log("tata !");
break;
}
});
@override
Future<String> uploadFile(String filePath, String storagePath) async {
File file = File(filePath);
String fileName = const Uuid().v4(); /// Generate a unique file name.
final fileRef = storageRef.child('$storagePath$fileName');
try {
await fileRef.putFile(file);
log("File uploaded successfully");
return fileRef.getDownloadURL();
} on FirebaseException catch (e) {
log("Failed to upload file: $e");
throw Exception(e);
}
}

@override
void deleteFile(String fileId) async {
void deleteFile(String fileURL) async {
log('deleteFile: $fileURL');
final fileId = bucket.refFromURL(fileURL).name;
final ref = storageRef.child(fileId);
await ref.delete();
}

@override
Future<void> downloadFile(String fileUrl) async {
// TODO: implement updateFile
}

@override
void updateFile(String fileName) {
// TODO: implement updateFile
Future<Uint8List?> downloadFileBytes(String fileURL) async {
log("downloadFileBytes: $fileURL");
final ref = bucket.refFromURL(fileURL);
try {
return await ref.getData(maxFileSize);
} on FirebaseException catch (e) {
log("Failed to download file: $e");
throw Exception(e);
}
}
}
9 changes: 8 additions & 1 deletion lib/api/firebase_user.dart
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class FirebaseUser extends FirebaseAPI implements IUser {
}

@override
void updateUser(User user) {
Future<void> updateUser(User user) async {
collectionReference
.doc(user.uid)
.update(user.toFirestore())
Expand Down Expand Up @@ -88,4 +88,11 @@ class FirebaseUser extends FirebaseAPI implements IUser {

return dietitians.isNotEmpty ? dietitians.first : null;
}

@override
Future<void> addClient(String userId, String dietitianId) async {
final dietitian = await readUser(dietitianId);
dietitian.addUser(userId);
await updateUser(dietitian);
}
}
15 changes: 10 additions & 5 deletions lib/api/ifile.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import 'dart:io';
import 'dart:typed_data';

/// Interface for file storage operations.
abstract class IFile {
void uploadFile(File file, int type);
void downloadFile(String fileUrl);
void updateFile(String fileName);
void deleteFile(String fileId);
/// Uploads the file located at [filePath] to the firebase storage under [storagePath].
/// Returns the download URL.
Future<String> uploadFile(String filePath, String storagePath);
/// Downloads the file located at [fileURL] from the firebase storage.
/// Returns the file bytes.
Future<Uint8List?> downloadFileBytes(String fileURL);
/// Deletes the file located at [fileURL] from the firebase storage.
void deleteFile(String fileURL);
}
3 changes: 2 additions & 1 deletion lib/api/iuser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import 'package:pdg_app/model/user.dart';
abstract class IUser {
Future<void> createUser(User user);
Future<User> readUser(String userid);
void updateUser(User user);
Future<void> updateUser(User user);
Future<void> addClient(String userId, String dietitianId);
void deleteUser(String userid);
Future<List<User>> getDietitianClient(String dietitianId);
Future<User?> readDietitianOfClient(String clientId);
Expand Down
1 change: 1 addition & 0 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ void main() async {
),
]);
await setup();

runApp(MyApp());
}

Expand Down
4 changes: 4 additions & 0 deletions lib/model/meal.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ class Meal implements IModel {
String? setting;
String? comment;
String owner;
String? photoUrl;

Meal(
{String? uid,
Expand All @@ -25,6 +26,7 @@ class Meal implements IModel {
required this.hunger,
this.setting,
this.comment,
this.photoUrl,
required this.owner})
: uid = uid ?? const Uuid().v1();

Expand All @@ -44,6 +46,7 @@ class Meal implements IModel {
setting: data?['setting'],
comment: data?['comment'],
owner: data?['owner'],
photoUrl: data?['photoUrl'],
);
}

Expand All @@ -60,6 +63,7 @@ class Meal implements IModel {
'setting': setting,
'comment': comment,
'owner': owner,
'photoUrl': photoUrl,
};
}

Expand Down
7 changes: 7 additions & 0 deletions lib/model/user.dart
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,11 @@ class User implements IModel {

@override
int get hashCode => Object.hash(uid, null);

void addUser(String userId) {
if (clientList == null) {
throw Exception("Client list is null");
}
clientList!.add(userId);
}
}
6 changes: 5 additions & 1 deletion lib/screens/diary.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'package:auto_route/auto_route.dart';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.dart';
import 'package:intl/intl.dart';
Expand All @@ -9,6 +10,8 @@ import 'package:pdg_app/widgets/cards/arrow_pic_card.dart';
import 'package:provider/provider.dart';
import 'package:table_calendar/table_calendar.dart';

import '../api/firebase_document.dart';
import '../api/ifile.dart';
import '../provider/auth_provider.dart';
import '../widgets/buttons/action_button.dart';
import '../widgets/diary/diary_top_bar.dart';
Expand All @@ -23,8 +26,9 @@ class DiaryScreen extends StatefulWidget {

class _DiaryScreenState extends State<DiaryScreen> {
DateTime _selectedDate = DateTime.now();
IFile fileApi = FirebaseFile(FirebaseStorage.instance);

_onDaySelected(DateTime day) {
_onDaySelected(DateTime day) async {
_selectedDate = day;
}

Expand Down
24 changes: 24 additions & 0 deletions lib/scripts/app_run.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import 'dart:developer';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:pdg_app/api/firebase_user.dart';
import 'package:pdg_app/api/iuser.dart';
import 'package:pdg_app/firebase_options.dart';

void main() async {
WidgetsFlutterBinding.ensureInitialized();

await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
runApp(const MaterialApp());

IUser userApi = FirebaseUser(FirebaseFirestore.instance);

await userApi.addClient("coco", "PSCOEhz98TORfOb9BizGfjUA8hc2");
final coco = await userApi.readUser("PSCOEhz98TORfOb9BizGfjUA8hc2");
log(coco.clientList.toString());
log("programme terminé");
}
16 changes: 15 additions & 1 deletion pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -268,12 +268,19 @@ packages:
source: hosted
version: "2.0.1"
file:
dependency: transitive
dependency: "direct main"
description:
name: file
url: "https://pub.dartlang.org"
source: hosted
version: "6.1.4"
file_picker:
dependency: "direct main"
description:
name: file_picker
url: "https://pub.dartlang.org"
source: hosted
version: "3.0.4"
firebase_auth:
dependency: "direct main"
description:
Expand Down Expand Up @@ -351,6 +358,13 @@ packages:
url: "https://pub.dartlang.org"
source: hosted
version: "10.3.7"
firebase_storage_mocks:
dependency: "direct main"
description:
name: firebase_storage_mocks
url: "https://pub.dartlang.org"
source: hosted
version: "0.5.1"
firebase_storage_platform_interface:
dependency: transitive
description:
Expand Down
3 changes: 3 additions & 0 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ dependencies:
path_provider: ^2.0.11
get_it: ^7.2.0
firebase_auth_mocks: ^0.8.5+1
firebase_storage_mocks: ^0.5.1
file_picker: ^3.0.4
file: ^6.1.4
awesome_snackbar_content: ^0.0.8
sorted_list: ^1.0.0

Expand Down
46 changes: 46 additions & 0 deletions test/file_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import 'dart:io';

import 'package:file/memory.dart';
import 'package:firebase_storage_mocks/firebase_storage_mocks.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pdg_app/api/firebase_document.dart';
import 'package:pdg_app/api/ifile.dart';

const filename = 'someimage.png';
final storage = MockFirebaseStorage();

void main() {
late IFile fileApi;

setUp(() async {
fileApi = FirebaseFile(storage);
});

test("Upload file", () async {
String filepath = await fileApi.uploadFile(getFakeImageFile().path, 'images/');
expect(filepath, isNotNull);
});

test("Delete file", () async {
String filepath = await fileApi.uploadFile(getFakeImageFile().path, 'images/');
fileApi.deleteFile(filepath);
expect(storage.storedDataMap.isEmpty, isTrue);
});

test("Download file bytes", () async {
/*
String filename = await fileApi.uploadFile(getFakeImageFile().path, 'images/');
Uint8List? bytes = await fileApi.downloadFileBytes(filename);
expect(bytes, isNotNull);
expect(bytes?.length, greaterThan(0));*/
expect(true, isTrue); // Mock doesnt work for download
});
}

/// Returns a fake image file.
File getFakeImageFile() {
var fs = MemoryFileSystem();
final image = fs.file(filename);
image.writeAsStringSync('contents');
return image;
}
1 change: 1 addition & 0 deletions test/test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
YOOOOOOOOOOOOOOOOOO
10 changes: 8 additions & 2 deletions test/user_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ User d1 = User(
lastName: 'Emery',
birthDate: DateTime.now(),
avs: '',
clientList: [c2.uid, c3.uid, c4.uid],
clientList: [c2.uid, c3.uid],
phoneNumber: '',
email: '[email protected]');
User d2 = User(
Expand Down Expand Up @@ -125,7 +125,7 @@ void main() {
});

test("getDietitianClients", () async {
List<User> coco = [c2, c3, c4];
List<User> coco = [c2, c3];
final clients = await userApi.getDietitianClient(d1.uid);
expect(clients.elementAt(0).toString(), coco.elementAt(0).toString());
});
Expand All @@ -134,4 +134,10 @@ void main() {
final User? dietCopy = await userApi.readDietitianOfClient(c3.uid);
expect(d1.toString(), dietCopy.toString());
});

test("Add Client to dietitian", () async {
await userApi.addClient("banane", d1.uid);
final User diet = await userApi.readUser(d1.uid);
expect(diet.clientList, [c2.uid, c3.uid, "banane"]);
});
}

0 comments on commit 12e88ba

Please sign in to comment.