Skip to content

Instantly share code, notes, and snippets.

@ansisec
Last active December 6, 2023 08:20
Show Gist options
  • Save ansisec/5f852a29e5a46f995d6003b6002f4926 to your computer and use it in GitHub Desktop.
Save ansisec/5f852a29e5a46f995d6003b6002f4926 to your computer and use it in GitHub Desktop.
Firebase Example
Ficheiros auxiliares
class FAuthUtil {
companion object {
private val auth by lazy { Firebase.auth }
val currentUser: FirebaseUser?
get() = auth.currentUser
fun createUserWithEmail(email: String, password: String, onResult: (Throwable?) -> Unit) {
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener { result ->
onResult(result.exception)
}
}
fun signInWithEmail(email: String, password: String, onResult: (Throwable?) -> Unit) {
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener { result ->
onResult(result.exception)
}
}
fun signOut() {
if (auth.currentUser != null) {
auth.signOut()
}
}
}
}
fun createUserWithEmail(email: String, password: String) {
if (email.isBlank() || password.isBlank())
return
viewModelScope.launch {
FAuthUtil.createUserWithEmail(email, password) { exception ->
if (exception == null)
_user.value = FAuthUtil.currentUser?.toUser()
_error.value = exception?.message
}
}
}
fun signInWithEmail(email: String, password: String) {
if (email.isBlank() || password.isBlank())
return
viewModelScope.launch {
FAuthUtil.signInWithEmail(email, password) { exception ->
if (exception == null)
_user.value = FAuthUtil.currentUser?.toUser()
_error.value = exception?.message
}
}
}
fun signOut() {
FAuthUtil.signOut()
_user.value = null
_error.value = null
}
private val _nrgames = mutableLongStateOf(0L)
val nrgames : MutableState<Long>
get() = _nrgames
private val _topscore = mutableLongStateOf(0L)
val topscore : MutableState<Long>
get() = _topscore
fun addDataToFirestore() {
viewModelScope.launch {
FStorageUtil.addDataToFirestore { exception ->
_error.value = exception?.message
}
}
}
fun updateDataInFirestore() {
viewModelScope.launch {
//FirebaseUtils.updateDataInFirestore()
FStorageUtil.updateDataInFirestoreTrans { exception ->
_error.value = exception?.message
}
}
}
fun removeDataFromFirestore() {
viewModelScope.launch {
FStorageUtil.removeDataFromFirestore { exception ->
_error.value = exception?.message
}
}
}
fun startObserver() {
viewModelScope.launch {
FStorageUtil.startObserver { g, t ->
_nrgames.longValue = g
_topscore.longValue = t
}
}
}
fun stopObserver() {
viewModelScope.launch {
FStorageUtil.stopObserver()
}
}
class FStorageUtil {
companion object {
fun addDataToFirestore(onResult: (Throwable?) -> Unit) {
val db = Firebase.firestore
val scores = hashMapOf(
"nrgames" to 0,
"topscore" to 0
)
db.collection("Scores").document("Level1").set(scores)
.addOnCompleteListener { result ->
onResult(result.exception)
}
}
fun updateDataInFirestore(onResult: (Throwable?) -> Unit) {
val db = Firebase.firestore
val v = db.collection("Scores").document("Level1")
v.get(Source.SERVER)
.addOnSuccessListener {
val exists = it.exists()
Log.i("Firestore", "updateDataInFirestore: Success? $exists")
if (!exists) {
onResult(Exception("Doesn't exist"))
return@addOnSuccessListener
}
val value = it.getLong("nrgames") ?: 0
v.update("nrgames", value + 1)
onResult(null)
}
.addOnFailureListener { e ->
onResult(e)
}
}
fun updateDataInFirestoreTrans(onResult: (Throwable?) -> Unit) {
val db = Firebase.firestore
val v = db.collection("Scores").document("Level1")
db.runTransaction { transaction ->
val doc = transaction.get(v)
if (doc.exists()) {
val newnrgames = (doc.getLong("nrgames") ?: 0) + 1
val newtopscore = (doc.getLong("topscore") ?: 0) + 100
transaction.update(v, "nrgames", newnrgames)
transaction.update(v, "topscore", newtopscore)
null
} else
throw FirebaseFirestoreException(
"Doesn't exist",
FirebaseFirestoreException.Code.UNAVAILABLE
)
}.addOnCompleteListener { result ->
onResult(result.exception)
}
}
fun removeDataFromFirestore(onResult: (Throwable?) -> Unit) {
val db = Firebase.firestore
val v = db.collection("Scores").document("Level1")
v.delete()
.addOnCompleteListener { onResult(it.exception) }
}
private var listenerRegistration: ListenerRegistration? = null
fun startObserver(onNewValues: (Long, Long) -> Unit) {
stopObserver()
val db = Firebase.firestore
listenerRegistration = db.collection("Scores").document("Level1")
.addSnapshotListener { docSS, e ->
if (e != null) {
return@addSnapshotListener
}
if (docSS != null && docSS.exists()) {
val nrgames = docSS.getLong("nrgames") ?: 0
val topscore = docSS.getLong("topscore") ?: 0
Log.i("Firestore", "$nrgames : $topscore")
onNewValues(nrgames, topscore)
}
}
}
fun stopObserver() {
listenerRegistration?.remove()
}
// Storage
fun getFileFromAsset(assetManager: AssetManager, strName: String): InputStream? {
var istr: InputStream? = null
try {
istr = assetManager.open(strName)
} catch (e: IOException) {
e.printStackTrace()
}
return istr
}
//https://firebase.google.com/docs/storage/android/upload-files
fun uploadFile(inputStream: InputStream, imgFile: String) {
val storage = Firebase.storage
val ref1 = storage.reference
val ref2 = ref1.child("images")
val ref3 = ref2.child(imgFile)
val uploadTask = ref3.putStream(inputStream)
uploadTask.continueWithTask { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
ref3.downloadUrl
}.addOnCompleteListener { task ->
if (task.isSuccessful) {
val downloadUri = task.result
println(downloadUri.toString())
} else {
// Handle failures
// ...
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment