Search in sources :

Example 6 with StorageReference

use of com.google.firebase.storage.StorageReference in project Tapad by berict.

the class PresetStoreActivity method isFirebaseMetadataUpdated.

private boolean isFirebaseMetadataUpdated(Context context) {
    isFMUpdated = false;
    if (isConnected(context)) {
        Log.d(TAG, "Connected to the internet");
        StorageReference metadataReference = FirebaseStorage.getInstance().getReferenceFromUrl("gs://tapad-4d342.appspot.com/presets").child("metadata.txt");
        metadataReference.getMetadata().addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {

            @Override
            public void onSuccess(StorageMetadata storageMetadata) {
                Log.d(TAG, "Successful getting metadata");
                if (storageMetadata.getUpdatedTimeMillis() > new File(metadataLocation).lastModified()) {
                    // firebase metadata is updated since last download
                    // get the new updated metadata
                    Log.d(TAG, "File updated");
                    isFMUpdated = true;
                } else {
                    Log.d(TAG, "File not updated");
                    isFMUpdated = false;
                }
            }
        }).addOnFailureListener(new OnFailureListener() {

            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d(TAG, "Failed to get metadata");
                isFMUpdated = false;
            }
        });
        return isFMUpdated;
    } else {
        Log.d(TAG, "Disconnected from the internet");
        return isFMUpdated;
    }
}
Also used : StorageMetadata(com.google.firebase.storage.StorageMetadata) StorageReference(com.google.firebase.storage.StorageReference) OnSuccessListener(com.google.android.gms.tasks.OnSuccessListener) File(java.io.File) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 7 with StorageReference

use of com.google.firebase.storage.StorageReference in project Tapad by berict.

the class FirebaseHelper method downloadFirebase.

public void downloadFirebase(String firebaseLocation, String fileLocation, Runnable onSuccess, Runnable onFailure, Activity activity) {
    FirebaseApp.initializeApp(activity);
    StorageReference storageReference = FirebaseStorage.getInstance().getReferenceFromUrl(FIREBASE_LOCATION + "/" + firebaseLocation);
    this.saveFromFirebase(storageReference, PROJECT_LOCATION + "/" + fileLocation, onSuccess, onFailure, activity);
}
Also used : StorageReference(com.google.firebase.storage.StorageReference)

Example 8 with StorageReference

use of com.google.firebase.storage.StorageReference in project Tapad by berict.

the class FirebaseHelper method getFirebaseMetadata.

public FirebaseMetadata getFirebaseMetadata(Activity activity) {
    FileHelper fileHelper = new FileHelper();
    FirebaseApp.initializeApp(activity);
    String metadataLocation = PROJECT_LOCATION_PRESET_METADATA;
    StorageReference metadataReference = FirebaseStorage.getInstance().getReferenceFromUrl(FIREBASE_LOCATION_PRESETS_METADATA);
    if (new File(metadataLocation).exists()) {
        // metadata file exists
        String metadata = fileHelper.getStringFromFile(metadataLocation);
        if (getStorageMetadata(metadataReference, activity).getUpdatedTimeMillis() > new File(metadataLocation).lastModified()) {
            // updated, download new one
            return saveFirebaseMetadata(metadataReference, metadataLocation, activity);
        } else {
            // offline or not updated, continue
            Gson gson = new Gson();
            FirebaseMetadata firebaseMetadata = gson.fromJson(metadata, FirebaseMetadata.class);
            if (firebaseMetadata.getPresets() == null || firebaseMetadata.getVersionCode() == null) {
                // corrupted metadata, download again
                return saveFirebaseMetadata(metadataReference, metadataLocation, activity);
            } else {
                return firebaseMetadata;
            }
        }
    } else {
        return saveFirebaseMetadata(metadataReference, metadataLocation, activity);
    }
}
Also used : FirebaseMetadata(com.bedrock.padder.model.FirebaseMetadata) StorageReference(com.google.firebase.storage.StorageReference) Gson(com.google.gson.Gson) File(java.io.File)

Example 9 with StorageReference

use of com.google.firebase.storage.StorageReference in project MadMax by deviz92.

the class ProfileEdit method updateAccount.

private boolean updateAccount() {
    Log.i(TAG, "createAccount");
    if (!validateForm()) {
        Log.i(TAG, "submitted form is not valid");
        Toast.makeText(this, "Invalid form!", Toast.LENGTH_SHORT).show();
        return false;
    }
    final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user == null) {
        Log.e(TAG, "Error while retriving current user from db");
        Toast.makeText(this, "Error while retriving current user from db", Toast.LENGTH_LONG).show();
        return false;
    }
    final String currentUserID = currentUser.getID();
    String newName = nameView.getText().toString();
    String newSurname = surnameView.getText().toString();
    String newUsername = usernameView.getText().toString();
    //String newEmail = emailView.getText().toString();
    String newPassword = passwordView.getText().toString();
    if (!newName.isEmpty() && (currentUser.getName() == null || !currentUser.getName().equals(newName))) {
        currentUser.setName(newName);
        databaseReference.child("users").child(currentUserID).child("name").setValue(currentUser.getName());
    }
    if (!newSurname.isEmpty() && (currentUser.getSurname() == null || !currentUser.getSurname().equals(newSurname))) {
        currentUser.setSurname(newSurname);
        databaseReference.child("users").child(currentUserID).child("surname").setValue(currentUser.getSurname());
    }
    if (!newUsername.isEmpty() && (currentUser.getUsername() == null || !currentUser.getUsername().equals(newUsername))) {
        currentUser.setUsername(newUsername);
        databaseReference.child("users").child(currentUserID).child("username").setValue(currentUser.getUsername());
    }
    if (IMAGE_CHANGED) {
        // for saving image
        StorageReference uProfileImageFilenameRef = storageReference.child("users").child(currentUserID).child(currentUserID + "_profileImage.jpg");
        // Get the data from an ImageView as bytes
        profileImageView.setDrawingCacheEnabled(true);
        profileImageView.buildDrawingCache();
        Bitmap bitmap = profileImageView.getDrawingCache();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] data = baos.toByteArray();
        UploadTask uploadTask = uProfileImageFilenameRef.putBytes(data);
        uploadTask.addOnFailureListener(new OnFailureListener() {

            @Override
            public void onFailure(@NonNull Exception exception) {
                // todo Handle unsuccessful uploads
                Log.e(TAG, "image upload failed");
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                currentUser.setProfileImage(taskSnapshot.getMetadata().getDownloadUrl().toString());
                databaseReference.child("users").child(currentUserID).child("image").setValue(currentUser.getProfileImage());
            }
        });
    }
    if (!newPassword.isEmpty() && !currentUser.getPassword().equals(User.encryptPassword(newPassword))) {
        try {
            user.updatePassword(newPassword);
        } catch (Exception e) {
            Log.e(TAG, e.getClass().toString() + ", message: " + e.getMessage());
            Toast.makeText(this, "Can't update password", Toast.LENGTH_LONG).show();
            return false;
        }
        currentUser.setPassword(newPassword);
        databaseReference.child("users").child(currentUserID).child("password").setValue(currentUser.getPassword());
    }
    return true;
}
Also used : StorageReference(com.google.firebase.storage.StorageReference) FirebaseUser(com.google.firebase.auth.FirebaseUser) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Bitmap(android.graphics.Bitmap) UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Example 10 with StorageReference

use of com.google.firebase.storage.StorageReference in project MadMax by deviz92.

the class SignUpFragment method sendVerificationEmail.

private void sendVerificationEmail() {
    Log.i(TAG, "sendVerificationEmail");
    final FirebaseUser user = auth.getCurrentUser();
    if (user == null) {
        Log.e(TAG, "Error while retriving current user from db");
        Toast.makeText(getContext(), "Error while retriving current user from db", Toast.LENGTH_LONG).show();
        return;
    }
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this.getContext());
    String defaultCurrency = sharedPref.getString(SettingsFragment.DEFAULT_CURRENCY, "");
    String UID = user.getUid();
    final User u = new User(UID, usernameView.getText().toString(), nameView.getText().toString(), surnameView.getText().toString(), emailView.getText().toString(), passwordView.getText().toString(), "", defaultCurrency);
    progressDialog.setMessage("Sending email verification, please wait...");
    progressDialog.show();
    // for saving image
    if (imageSetted) {
        StorageReference uProfileImageFilenameRef = storageReference.child("users").child(UID).child(UID + "_profileImage.jpg");
        // Get the data from an ImageView as bytes
        profileImageView.setDrawingCacheEnabled(true);
        profileImageView.buildDrawingCache();
        Bitmap bitmap = profileImageView.getDrawingCache();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] data = baos.toByteArray();
        UploadTask uploadTask = uProfileImageFilenameRef.putBytes(data);
        uploadTask.addOnFailureListener(new OnFailureListener() {

            @Override
            public void onFailure(@NonNull Exception exception) {
                // todo Handle unsuccessful uploads
                Log.e(TAG, "image upload failed");
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {

            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
                u.setProfileImage(taskSnapshot.getMetadata().getDownloadUrl().toString());
                user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {

                    @Override
                    public void onComplete(@NonNull Task<Void> task) {
                        progressDialog.dismiss();
                        if (task.isSuccessful()) {
                            Log.i(TAG, "verification email successful sent");
                            Log.i(TAG, "insert new user into db");
                            HashMap<String, String> newUserEntry = new HashMap<>();
                            newUserEntry.put("email", u.getEmail());
                            newUserEntry.put("password", u.getPassword());
                            //                                    newUserEntry.put("friends", u.getUserFriends().toString());
                            //                                    newUserEntry.put("groups", u.getUserGroups().toString());
                            newUserEntry.put("image", u.getProfileImage());
                            newUserEntry.put("name", u.getName());
                            newUserEntry.put("surname", u.getSurname());
                            newUserEntry.put("username", u.getUsername());
                            databaseReference.child("users").child(u.getID()).setValue(newUserEntry);
                            Toast.makeText(getContext(), R.string.emailVerification_text, Toast.LENGTH_LONG).show();
                        } else {
                            // todo delete the account and restart the activity
                            Log.e(TAG, "verification email not sent, exception: " + task.getException());
                        }
                        onClickSignUpInterface.itemClicked(SignUpFragment.class.getSimpleName(), "1");
                    }
                });
            }
        });
    } else {
        user.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {

            @Override
            public void onComplete(@NonNull Task<Void> task) {
                progressDialog.dismiss();
                if (task.isSuccessful()) {
                    Log.i(TAG, "verification email successful sent");
                    Log.i(TAG, "insert new user into db");
                    HashMap<String, String> newUserEntry = new HashMap<>();
                    newUserEntry.put("email", u.getEmail());
                    newUserEntry.put("password", u.getPassword());
                    //                        newUserEntry.put("friends", u.getUserFriends().toString());
                    //                        newUserEntry.put("groups", u.getUserGroups().toString());
                    newUserEntry.put("image", u.getProfileImage());
                    newUserEntry.put("name", u.getName());
                    newUserEntry.put("surname", u.getSurname());
                    newUserEntry.put("username", u.getUsername());
                    databaseReference.child("users").child(u.getID()).setValue(newUserEntry);
                    Toast.makeText(getContext(), R.string.emailVerification_text, Toast.LENGTH_LONG).show();
                } else {
                    // todo delete the account and restart the activity
                    Log.e(TAG, "verification email not sent, exception: " + task.getException());
                }
                onClickSignUpInterface.itemClicked(SignUpFragment.class.getSimpleName(), "1");
            }
        });
    }
}
Also used : Task(com.google.android.gms.tasks.Task) UploadTask(com.google.firebase.storage.UploadTask) User(com.polito.mad17.madmax.entities.User) FirebaseUser(com.google.firebase.auth.FirebaseUser) HashMap(java.util.HashMap) Bitmap(android.graphics.Bitmap) UploadTask(com.google.firebase.storage.UploadTask) NonNull(android.support.annotation.NonNull) StorageReference(com.google.firebase.storage.StorageReference) SharedPreferences(android.content.SharedPreferences) FirebaseUser(com.google.firebase.auth.FirebaseUser) ByteArrayOutputStream(java.io.ByteArrayOutputStream) FirebaseAuthWeakPasswordException(com.google.firebase.auth.FirebaseAuthWeakPasswordException) FirebaseAuthUserCollisionException(com.google.firebase.auth.FirebaseAuthUserCollisionException) IOException(java.io.IOException) OnCompleteListener(com.google.android.gms.tasks.OnCompleteListener) OnFailureListener(com.google.android.gms.tasks.OnFailureListener)

Aggregations

StorageReference (com.google.firebase.storage.StorageReference)12 OnFailureListener (com.google.android.gms.tasks.OnFailureListener)8 UploadTask (com.google.firebase.storage.UploadTask)6 Bitmap (android.graphics.Bitmap)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 NonNull (android.support.annotation.NonNull)4 OnSuccessListener (com.google.android.gms.tasks.OnSuccessListener)4 File (java.io.File)4 HashMap (java.util.HashMap)3 FirebaseUser (com.google.firebase.auth.FirebaseUser)2 StorageMetadata (com.google.firebase.storage.StorageMetadata)2 User (com.polito.mad17.madmax.entities.User)2 SimpleDateFormat (java.text.SimpleDateFormat)2 Map (java.util.Map)2 TreeMap (java.util.TreeMap)2 Intent (android.content.Intent)1 SharedPreferences (android.content.SharedPreferences)1 Uri (android.net.Uri)1 MotionEvent (android.view.MotionEvent)1 FirebaseMetadata (com.bedrock.padder.model.FirebaseMetadata)1