Skip to content

Revamped Book and User Collections #129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Oct 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions lib/providers/book.dart
Original file line number Diff line number Diff line change
@@ -1,43 +1,43 @@
import 'package:flutter/cupertino.dart';

class Book with ChangeNotifier {
final String id;
// final String id;
final String isbn;
final String title;
final String author;
final String imageUrl;
final String userid;
double rating;
final String description;
final String category;
final String genre;
bool isBookMarked;
bool isOwned;
bool isLent;
bool isBorrowed;
final String pages;
final int pages;
final String infoLink;
// ignore: sort_constructors_first

Book({
this.infoLink,
this.id,
// this.id,
this.isbn,
this.title,
this.author,
this.imageUrl,
this.userid,
this.description,
this.genre,
this.rating = 0,
this.isBookMarked = false,
this.isOwned = false,
this.isLent = false,
this.isBorrowed = false,
this.description,
this.category,
this.pages,
// this.category,
this.pages = 0,
this.infoLink,
});
//change isBookMarkedStatus
void changeBookMark() {
isBookMarked = !isBookMarked;
notifyListeners();
}


}

64 changes: 53 additions & 11 deletions lib/providers/books.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'dart:convert';

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:http/http.dart' as http;

Expand Down Expand Up @@ -97,25 +98,67 @@ class Books with ChangeNotifier {
// }
// return result;
// }
Future<dynamic> getBooksbyISBN(String isbn) async {
Future<dynamic> getBooksbyISBN(String isbn) async {
//Add Books from Google API
const String url = 'https://www.googleapis.com/books/v1/volumes?q=isbn';
const String url = 'https://www.googleapis.com/books/v1/volumes?q=isbn:';
final Map<String, dynamic> res = <String, dynamic>{
'kind': 'books#volumes',
'totalItems': 0
};
try {
final http.Response response = await http.get(url + isbn);
final http.Response response = await http.get(url + isbn.trim());
final dynamic result = jsonDecode(response.body);
// print("Result From get Books From ISBN:");

// print(result);
if (result != null) {
return result;
}
return null;
// print(result["items"][0]);
return result;
} catch (e) {
print(e.toString());
}
return null;
return res;
}

Book makeBookforDB(dynamic result, String isbnCode) {
// print(result);
Book book;

// final String id = result['items'][0]['id'] as String;
final String title = result['items'][0]['volumeInfo']['title'] as String;
final String author =
result['items'][0]['volumeInfo']['authors'][0] as String;
final String description =
result['items'][0]['volumeInfo']['description'] as String;
final String isbn = isbnCode;
final String infoLink =
result['items'][0]['volumeInfo']['infoLink'] as String;
final int pages = result['items'][0]['volumeInfo']['pageCount'] as int;
String imageLink;
try {
imageLink =
result['items'][0]['volumeInfo']['imageLinks']['thumbnail'] as String;
imageLink = imageLink.replaceFirst('http', 'https', 0);
} catch (e) {
imageLink =
'https://upload.wikimedia.org/wikipedia/commons/thumb/6/65/No-Image-Placeholder.svg/1200px-No-Image-Placeholder.svg.png';
print('imageLink is empty');
}

print(FirebaseAuth.instance.currentUser.uid);
print('ISBN' + isbn.toString());
print('Title:' + title.toString());
print('Author:' + author.toString());
print('ImageLink:' + imageLink.toString());
print('Description' + description.toString());
book = Book(
isbn: isbn,
title: title,
author: author,
imageUrl: imageLink,
description: description,
isOwned: true,
pages: pages ?? 0,
infoLink: infoLink);
return book;
}

// Future<dynamic> getBooksbyTitle(String title) async {
// final Response response =
Expand Down Expand Up @@ -236,7 +279,6 @@ Future<dynamic> getBooksbyISBN(String isbn) async {
}
}


Future<dynamic> getISBNFromName(String title) async {
const String url = 'https://www.googleapis.com/books/v1/volumes?q=';
try {
Expand Down
3 changes: 0 additions & 3 deletions lib/providers/user.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@


class UserData {
String uid;
String displayName;
Expand Down Expand Up @@ -33,4 +31,3 @@ class UserData {
this.preferences,
this.locationRange});
}

98 changes: 37 additions & 61 deletions lib/screens/add_book.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ class AddBook extends StatefulWidget {
}

class _AddBookState extends State<AddBook> {
final FirebaseAuthService _authService =
FirebaseAuthService();
final FirebaseAuthService _authService = FirebaseAuthService();
final GlobalKey<FormState> _bookKey = GlobalKey<FormState>();
final TextEditingController _bookName = TextEditingController();
final TextEditingController _authorName = TextEditingController();
Expand Down Expand Up @@ -128,34 +127,43 @@ class _AddBookState extends State<AddBook> {
padding: const EdgeInsets.all(10.0),
// child: button(context, blackButton, 'Add your Book', ''),
child: Button(
name: 'Add your Book',
color: blackButton,
myFunction: () async {
if (_bookKey.currentState.validate()) {
_bookKey.currentState.save();
final dynamic result =
await bookList.getBooksbyISBN(_isbnCode.text);
if (result != null) {
final Book book = makeBook(result);
// bookList.postAddedBook(book);
await _databaseService.addBook(book);

final SnackBar snackbar = SnackBar(
content: const Text('Your book has been added'),
action: SnackBarAction(
label: 'Close',
onPressed: () {
ScaffoldMessenger.of(context)
.hideCurrentSnackBar();
},
),
);
ScaffoldMessenger.of(context)
.showSnackBar(snackbar);
name: 'Add your Book',
color: blackButton,
myFunction: () async {
if (_bookKey.currentState.validate()) {
_bookKey.currentState.save();
final dynamic result =
await bookList.getBooksbyISBN(_isbnCode.text);
if (result['totalItems'] != 0) {
final Book book = bookList.makeBookforDB(
result, _isbnCode.text);
// bookList.postAddedBook(book);
await _databaseService.addBook(book);
Navigator.of(context).pop();
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(
content: Text('Your book has been added',
style: TextStyle(color: blackButton)),
duration: Duration(seconds: 3),
// action: SnackBarAction(
// label: 'Close',
// onPressed: () {
// ScaffoldMessenger.of(context)
// .hideCurrentSnackBar();
// },
// ),
));
} else {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(
content: Text(
"Book not found in Google book's database"),
backgroundColor: blackButton,
duration: Duration(seconds: 3),
));
}
}
}
}
),
}),
),
],
),
Expand All @@ -166,36 +174,4 @@ class _AddBookState extends State<AddBook> {
),
);
}

//This Function is to Make Books FROM JSON result
//Add Book Driver
Book makeBook(dynamic result) {
Book book;
if (result != null) {
final String title = result['title'] as String;
final String author = result['author'] as String;
final String description = result['description'] as String;
final String isbn = result['isbn'] as String;
String imageLink = result['image'] as String;
imageLink = imageLink.replaceFirst('http', 'https', 0);

if (imageLink.isEmpty) {
print('imageLink is empty');
}
print('ISBN' + isbn);
print('Title:' + title);
print('Author:' + author);
print('ImageLink:' + imageLink);
print('Description' + description);
book = Book(
isbn: isbn,
title: title,
description: description,
imageUrl: imageLink,
author: author,
isOwned: true,
);
}
return book;
}
}
69 changes: 49 additions & 20 deletions lib/services/database_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class DatabaseService {
}

Stream<List<Book>> get booksData {
return booksCollection
return userDataCollection
.doc(uid)
.collection('ownedBooks')
.snapshots()
Expand All @@ -37,9 +37,29 @@ class DatabaseService {
}

//Update Users Location
Future addBook(Book book) async {
//GET BOOK FROM API or an existing List
return booksCollection
Future<void> addBook(Book book) async {
//GET BOOK FROM API or an existing List and adds to both users and books collection
await userDataCollection
.doc(uid)
.collection('ownedBooks')
.doc(book.isbn)
.set(<String, dynamic>{
'rating': book.rating,
'isbn': book.isbn,
'isBookMarked': book.isBookMarked,
'isOwned': book.isOwned ?? false,
'isLent': book.isLent,
'isBorrowed': book.isBorrowed,
'title': book.title,
'description': book.description,
'imageUrl': book.imageUrl,
'author': book.author,
'pages': book.pages,
'infoLink': book.infoLink,
'genre': book.genre,
'userid': uid
});
await booksCollection
.doc(uid)
.collection('ownedBooks')
.doc(book.isbn)
Expand All @@ -48,10 +68,16 @@ class DatabaseService {
'isbn': book.isbn,
'isBookMarked': book.isBookMarked,
'isOwned': book.isOwned ?? false,
'isLent': book.isLent,
'isBorrowed': book.isBorrowed,
'title': book.title,
'description': book.description,
'imageUrl': book.imageUrl,
'author': book.author
'author': book.author,
'pages': book.pages,
'infoLink': book.infoLink,
'genre': book.genre,
'userid': uid
});
}

Expand Down Expand Up @@ -89,7 +115,21 @@ class DatabaseService {
// // .map(_messageFromSnapshot);
// }


void removeBook(String isbn) {
print(isbn);
booksCollection
.doc(uid)
.collection('ownedBooks')
.doc(isbn)
.delete()
.catchError((dynamic e) => print(e.toString()));
userDataCollection
.doc(uid)
.collection('ownedBooks')
.doc(isbn)
.delete()
.catchError((dynamic e) => print(e.toString()));
}

// Future<DocumentReference> sendMessage(Message message) async {
// // final newMessage = Message(
Expand Down Expand Up @@ -119,26 +159,15 @@ class DatabaseService {
// // );
// //update receiver inbox
// }
void removeBook(String isbn) {
booksCollection
.doc(uid)
.collection('ownedBooks')
.doc(isbn)
.delete()
.catchError((dynamic e) => print(e.toString()));
}
Future<void> updateBookMark(Book book) async {
//Get
print("Hello there");

final DocumentReference docReference =
booksCollection.doc(uid).collection('ownedBooks').doc(book.isbn);
docReference.update(<String, dynamic>{
'isBookMarked': book.isBookMarked,
}

);

'isBookMarked': book.isBookMarked,
});
}

Future<void> updateGenres(List<String> genres) async {
Expand Down Expand Up @@ -232,7 +261,7 @@ class DatabaseService {
return snapshot.docs.map((QueryDocumentSnapshot doc) {
// print(doc.data);
return Book(
rating: doc.data()['rating'] as double,
// rating: doc.data()['rating'] as double,
isOwned: doc.data()['isOwned'] as bool,
isBookMarked: doc.data()['isBookMarked'] as bool,
imageUrl: doc.data()['imageUrl'] as String,
Expand Down