Search in sources :

Example 21 with ArbitraryDataProvider

use of com.owncloud.android.datamodel.ArbitraryDataProvider in project android by nextcloud.

the class FilesSyncHelper method insertContentIntoDB.

private static void insertContentIntoDB(Uri uri, SyncedFolder syncedFolder) {
    final Context context = MainApp.getAppContext();
    final ContentResolver contentResolver = context.getContentResolver();
    ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(contentResolver);
    Cursor cursor;
    int column_index_data;
    int column_index_date_modified;
    final FilesystemDataProvider filesystemDataProvider = new FilesystemDataProvider(contentResolver);
    String contentPath;
    boolean isFolder;
    String[] projection = { MediaStore.MediaColumns.DATA, MediaStore.MediaColumns.DATE_MODIFIED };
    String path = syncedFolder.getLocalPath();
    if (!path.endsWith("/")) {
        path = path + "/%";
    } else {
        path = path + "%";
    }
    String syncedFolderInitiatedKey = SYNCEDFOLDERINITIATED + syncedFolder.getId();
    String dateInitiated = arbitraryDataProvider.getValue(GLOBAL, syncedFolderInitiatedKey);
    cursor = context.getContentResolver().query(uri, projection, MediaStore.MediaColumns.DATA + " LIKE ?", new String[] { path }, null);
    if (cursor != null) {
        column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
        column_index_date_modified = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATE_MODIFIED);
        while (cursor.moveToNext()) {
            contentPath = cursor.getString(column_index_data);
            isFolder = new File(contentPath).isDirectory();
            if (cursor.getLong(column_index_date_modified) >= Long.parseLong(dateInitiated)) {
                filesystemDataProvider.storeOrUpdateFileValue(contentPath, cursor.getLong(column_index_date_modified), isFolder, syncedFolder);
            }
        }
        cursor.close();
    }
}
Also used : Context(android.content.Context) FilesystemDataProvider(com.owncloud.android.datamodel.FilesystemDataProvider) ArbitraryDataProvider(com.owncloud.android.datamodel.ArbitraryDataProvider) Cursor(android.database.Cursor) File(java.io.File) ContentResolver(android.content.ContentResolver)

Example 22 with ArbitraryDataProvider

use of com.owncloud.android.datamodel.ArbitraryDataProvider in project android by nextcloud.

the class PreferenceManager method getFolderPreference.

/**
 * Get preference value for a folder.
 * If folder is not set itself, it finds an ancestor that is set.
 *
 * @param context Context object.
 * @param preferenceName Name of the preference to lookup.
 * @param folder Folder.
 * @param defaultValue Fallback value in case no ancestor is set.
 * @return Preference value
 */
public static String getFolderPreference(Context context, String preferenceName, OCFile folder, String defaultValue) {
    Account account = AccountUtils.getCurrentOwnCloudAccount(context);
    if (account == null) {
        return defaultValue;
    }
    ArbitraryDataProvider dataProvider = new ArbitraryDataProvider(context.getContentResolver());
    FileDataStorageManager storageManager = ((ComponentsGetter) context).getStorageManager();
    if (storageManager == null) {
        storageManager = new FileDataStorageManager(account, context.getContentResolver());
    }
    String value = dataProvider.getValue(account.name, getKeyFromFolder(preferenceName, folder));
    while (folder != null && value.isEmpty()) {
        folder = storageManager.getFileById(folder.getParentId());
        value = dataProvider.getValue(account.name, getKeyFromFolder(preferenceName, folder));
    }
    return value.isEmpty() ? defaultValue : value;
}
Also used : ComponentsGetter(com.owncloud.android.ui.activity.ComponentsGetter) Account(android.accounts.Account) FileDataStorageManager(com.owncloud.android.datamodel.FileDataStorageManager) ArbitraryDataProvider(com.owncloud.android.datamodel.ArbitraryDataProvider)

Example 23 with ArbitraryDataProvider

use of com.owncloud.android.datamodel.ArbitraryDataProvider in project android by nextcloud.

the class AccountRemovalJob method onRunJob.

@NonNull
@Override
protected Result onRunJob(Params params) {
    Context context = MainApp.getAppContext();
    PersistableBundleCompat bundle = params.getExtras();
    Account account = AccountUtils.getOwnCloudAccountByName(context, bundle.getString(ACCOUNT, ""));
    AccountManager am = (AccountManager) context.getSystemService(ACCOUNT_SERVICE);
    if (account != null && am != null) {
        // disable contact backup job
        ContactsPreferenceActivity.cancelContactBackupJobForAccount(context, account);
        if (am != null) {
            am.removeAccount(account, this, null);
        }
        FileDataStorageManager storageManager = new FileDataStorageManager(account, context.getContentResolver());
        File tempDir = new File(FileStorageUtils.getTemporalPath(account.name));
        File saveDir = new File(FileStorageUtils.getSavePath(account.name));
        FileStorageUtils.deleteRecursively(tempDir, storageManager);
        FileStorageUtils.deleteRecursively(saveDir, storageManager);
        // delete all database entries
        storageManager.deleteAllFiles();
        // remove pending account removal
        ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(context.getContentResolver());
        arbitraryDataProvider.deleteKeyForAccount(account.name, PENDING_FOR_REMOVAL);
        // remove synced folders set for account
        SyncedFolderProvider syncedFolderProvider = new SyncedFolderProvider(context.getContentResolver());
        List<SyncedFolder> syncedFolders = syncedFolderProvider.getSyncedFolders();
        List<Long> syncedFolderIds = new ArrayList<>();
        for (SyncedFolder syncedFolder : syncedFolders) {
            if (syncedFolder.getAccount().equals(account.name)) {
                arbitraryDataProvider.deleteKeyForAccount(FilesSyncHelper.GLOBAL, FilesSyncHelper.SYNCEDFOLDERINITIATED + syncedFolder.getId());
                syncedFolderIds.add(syncedFolder.getId());
            }
        }
        syncedFolderProvider.deleteSyncFoldersForAccount(account);
        UploadsStorageManager uploadsStorageManager = new UploadsStorageManager(context.getContentResolver(), context);
        uploadsStorageManager.removeAccountUploads(account);
        FilesystemDataProvider filesystemDataProvider = new FilesystemDataProvider(context.getContentResolver());
        for (long syncedFolderId : syncedFolderIds) {
            filesystemDataProvider.deleteAllEntriesForSyncedFolder(Long.toString(syncedFolderId));
        }
        // delete stored E2E keys
        arbitraryDataProvider.deleteKeyForAccount(account.name, EncryptionUtils.PRIVATE_KEY);
        arbitraryDataProvider.deleteKeyForAccount(account.name, EncryptionUtils.PUBLIC_KEY);
        return Result.SUCCESS;
    } else {
        return Result.FAILURE;
    }
}
Also used : Context(android.content.Context) Account(android.accounts.Account) FilesystemDataProvider(com.owncloud.android.datamodel.FilesystemDataProvider) PersistableBundleCompat(com.evernote.android.job.util.support.PersistableBundleCompat) ArrayList(java.util.ArrayList) ArbitraryDataProvider(com.owncloud.android.datamodel.ArbitraryDataProvider) SyncedFolderProvider(com.owncloud.android.datamodel.SyncedFolderProvider) SyncedFolder(com.owncloud.android.datamodel.SyncedFolder) FileDataStorageManager(com.owncloud.android.datamodel.FileDataStorageManager) UploadsStorageManager(com.owncloud.android.datamodel.UploadsStorageManager) AccountManager(android.accounts.AccountManager) File(java.io.File) NonNull(android.support.annotation.NonNull)

Example 24 with ArbitraryDataProvider

use of com.owncloud.android.datamodel.ArbitraryDataProvider in project android by nextcloud.

the class FilesSyncJob method onRunJob.

@NonNull
@Override
protected Result onRunJob(Params params) {
    final Context context = MainApp.getAppContext();
    final ContentResolver contentResolver = context.getContentResolver();
    FileUploader.UploadRequester requester = new FileUploader.UploadRequester();
    PowerManager.WakeLock wakeLock = null;
    if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        wakeLock.acquire();
    }
    PersistableBundleCompat bundle = params.getExtras();
    final boolean skipCustom = bundle.getBoolean(SKIP_CUSTOM, false);
    final boolean overridePowerSaving = bundle.getBoolean(OVERRIDE_POWER_SAVING, false);
    // If we are in power save mode, better to postpone upload
    if (PowerUtils.isPowerSaveMode(context) && !overridePowerSaving) {
        wakeLock.release();
        return Result.SUCCESS;
    }
    Resources resources = MainApp.getAppContext().getResources();
    boolean lightVersion = resources.getBoolean(R.bool.syncedFolder_light);
    FilesSyncHelper.restartJobsIfNeeded();
    FilesSyncHelper.insertAllDBEntries(skipCustom);
    // Create all the providers we'll need
    final FilesystemDataProvider filesystemDataProvider = new FilesystemDataProvider(contentResolver);
    SyncedFolderProvider syncedFolderProvider = new SyncedFolderProvider(contentResolver);
    for (SyncedFolder syncedFolder : syncedFolderProvider.getSyncedFolders()) {
        if ((syncedFolder.isEnabled()) && (!skipCustom || MediaFolderType.CUSTOM != syncedFolder.getType())) {
            for (String path : filesystemDataProvider.getFilesForUpload(syncedFolder.getLocalPath(), Long.toString(syncedFolder.getId()))) {
                File file = new File(path);
                Long lastModificationTime = file.lastModified();
                final Locale currentLocale = context.getResources().getConfiguration().locale;
                if (MediaFolderType.IMAGE == syncedFolder.getType()) {
                    String mimeTypeString = FileStorageUtils.getMimeTypeFromName(file.getAbsolutePath());
                    if ("image/jpeg".equalsIgnoreCase(mimeTypeString) || "image/tiff".equalsIgnoreCase(mimeTypeString)) {
                        try {
                            ExifInterface exifInterface = new ExifInterface(file.getAbsolutePath());
                            String exifDate = exifInterface.getAttribute(ExifInterface.TAG_DATETIME);
                            if (!TextUtils.isEmpty(exifDate)) {
                                ParsePosition pos = new ParsePosition(0);
                                SimpleDateFormat sFormatter = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss", currentLocale);
                                sFormatter.setTimeZone(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
                                Date dateTime = sFormatter.parse(exifDate, pos);
                                lastModificationTime = dateTime.getTime();
                            }
                        } catch (IOException e) {
                            Log_OC.d(TAG, "Failed to get the proper time " + e.getLocalizedMessage());
                        }
                    }
                }
                String mimeType = MimeTypeUtil.getBestMimeTypeByFilename(file.getAbsolutePath());
                Account account = AccountUtils.getOwnCloudAccountByName(context, syncedFolder.getAccount());
                String remotePath;
                boolean subfolderByDate;
                Integer uploadAction;
                boolean needsCharging;
                boolean needsWifi;
                if (lightVersion) {
                    ArbitraryDataProvider arbitraryDataProvider = new ArbitraryDataProvider(context.getContentResolver());
                    needsCharging = resources.getBoolean(R.bool.syncedFolder_light_on_charging);
                    needsWifi = account == null || arbitraryDataProvider.getBooleanValue(account.name, Preferences.SYNCED_FOLDER_LIGHT_UPLOAD_ON_WIFI);
                    String uploadActionString = resources.getString(R.string.syncedFolder_light_upload_behaviour);
                    uploadAction = getUploadAction(uploadActionString);
                    subfolderByDate = resources.getBoolean(R.bool.syncedFolder_light_use_subfolders);
                    remotePath = resources.getString(R.string.syncedFolder_remote_folder);
                } else {
                    needsCharging = syncedFolder.getChargingOnly();
                    needsWifi = syncedFolder.getWifiOnly();
                    uploadAction = syncedFolder.getUploadAction();
                    subfolderByDate = syncedFolder.getSubfolderByDate();
                    remotePath = syncedFolder.getRemotePath();
                }
                if (!subfolderByDate) {
                    String adaptedPath = file.getAbsolutePath().replace(syncedFolder.getLocalPath(), "").replace("/" + file.getName(), "");
                    remotePath += adaptedPath;
                }
                requester.uploadFileWithOverwrite(context, account, file.getAbsolutePath(), FileStorageUtils.getInstantUploadFilePath(currentLocale, remotePath, file.getName(), lastModificationTime, subfolderByDate), uploadAction, mimeType, // create parent folder if not existent
                true, UploadFileOperation.CREATED_AS_INSTANT_PICTURE, needsWifi, needsCharging, true);
                filesystemDataProvider.updateFilesystemFileAsSentForUpload(path, Long.toString(syncedFolder.getId()));
            }
        }
    }
    if (wakeLock != null) {
        wakeLock.release();
    }
    return Result.SUCCESS;
}
Also used : Locale(java.util.Locale) FilesystemDataProvider(com.owncloud.android.datamodel.FilesystemDataProvider) Account(android.accounts.Account) PersistableBundleCompat(com.evernote.android.job.util.support.PersistableBundleCompat) FileUploader(com.owncloud.android.files.services.FileUploader) ContentResolver(android.content.ContentResolver) PowerManager(android.os.PowerManager) SyncedFolder(com.owncloud.android.datamodel.SyncedFolder) ParsePosition(java.text.ParsePosition) Context(android.content.Context) ExifInterface(android.support.media.ExifInterface) SyncedFolderProvider(com.owncloud.android.datamodel.SyncedFolderProvider) ArbitraryDataProvider(com.owncloud.android.datamodel.ArbitraryDataProvider) IOException(java.io.IOException) Date(java.util.Date) Resources(android.content.res.Resources) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat) NonNull(android.support.annotation.NonNull)

Example 25 with ArbitraryDataProvider

use of com.owncloud.android.datamodel.ArbitraryDataProvider in project android by nextcloud.

the class PushUtils method pushRegistrationToServer.

public static void pushRegistrationToServer() {
    String token = PreferenceManager.getPushToken(MainApp.getAppContext());
    arbitraryDataProvider = new ArbitraryDataProvider(MainApp.getAppContext().getContentResolver());
    if (!TextUtils.isEmpty(MainApp.getAppContext().getResources().getString(R.string.push_server_url)) && !TextUtils.isEmpty(token)) {
        PushUtils.generateRsa2048KeyPair();
        String pushTokenHash = PushUtils.generateSHA512Hash(token).toLowerCase(Locale.ROOT);
        PublicKey devicePublicKey = (PublicKey) PushUtils.readKeyFromFile(true);
        if (devicePublicKey != null) {
            byte[] publicKeyBytes = Base64.encode(devicePublicKey.getEncoded(), Base64.NO_WRAP);
            String publicKey = new String(publicKeyBytes);
            publicKey = publicKey.replaceAll("(.{64})", "$1\n");
            publicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----\n";
            Context context = MainApp.getAppContext();
            String providerValue;
            PushConfigurationState accountPushData = null;
            Gson gson = new Gson();
            for (Account account : AccountUtils.getAccounts(context)) {
                providerValue = arbitraryDataProvider.getValue(account, KEY_PUSH);
                if (!TextUtils.isEmpty(providerValue)) {
                    accountPushData = gson.fromJson(providerValue, PushConfigurationState.class);
                } else {
                    accountPushData = null;
                }
                if (accountPushData != null && !accountPushData.getPushToken().equals(token) && !accountPushData.isShouldBeDeleted() || TextUtils.isEmpty(providerValue)) {
                    try {
                        OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
                        OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, context);
                        RemoteOperation registerAccountDeviceForNotificationsOperation = new RegisterAccountDeviceForNotificationsOperation(pushTokenHash, publicKey, context.getResources().getString(R.string.push_server_url));
                        RemoteOperationResult remoteOperationResult = registerAccountDeviceForNotificationsOperation.execute(mClient);
                        if (remoteOperationResult.isSuccess()) {
                            PushResponse pushResponse = remoteOperationResult.getPushResponseData();
                            RemoteOperation registerAccountDeviceForProxyOperation = new RegisterAccountDeviceForProxyOperation(context.getResources().getString(R.string.push_server_url), token, pushResponse.getDeviceIdentifier(), pushResponse.getSignature(), pushResponse.getPublicKey());
                            remoteOperationResult = registerAccountDeviceForProxyOperation.execute(mClient);
                            if (remoteOperationResult.isSuccess()) {
                                PushConfigurationState pushArbitraryData = new PushConfigurationState(token, pushResponse.getDeviceIdentifier(), pushResponse.getSignature(), pushResponse.getPublicKey(), false);
                                arbitraryDataProvider.storeOrUpdateKeyValue(account.name, KEY_PUSH, gson.toJson(pushArbitraryData));
                            }
                        } else if (remoteOperationResult.getCode() == RemoteOperationResult.ResultCode.ACCOUNT_USES_STANDARD_PASSWORD) {
                            arbitraryDataProvider.storeOrUpdateKeyValue(account.name, AccountUtils.ACCOUNT_USES_STANDARD_PASSWORD, "true");
                        }
                    } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
                        Log_OC.d(TAG, "Failed to find an account");
                    } catch (AuthenticatorException e) {
                        Log_OC.d(TAG, "Failed via AuthenticatorException");
                    } catch (IOException e) {
                        Log_OC.d(TAG, "Failed via IOException");
                    } catch (OperationCanceledException e) {
                        Log_OC.d(TAG, "Failed via OperationCanceledException");
                    }
                } else if (accountPushData != null && accountPushData.isShouldBeDeleted()) {
                    deleteRegistrationForAccount(account);
                }
            }
        }
    }
}
Also used : Context(android.content.Context) Account(android.accounts.Account) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) RemoteOperation(com.owncloud.android.lib.common.operations.RemoteOperation) PublicKey(java.security.PublicKey) RemoteOperationResult(com.owncloud.android.lib.common.operations.RemoteOperationResult) OperationCanceledException(android.accounts.OperationCanceledException) RegisterAccountDeviceForNotificationsOperation(com.owncloud.android.lib.resources.notifications.RegisterAccountDeviceForNotificationsOperation) AccountUtils(com.owncloud.android.authentication.AccountUtils) ArbitraryDataProvider(com.owncloud.android.datamodel.ArbitraryDataProvider) Gson(com.google.gson.Gson) AuthenticatorException(android.accounts.AuthenticatorException) OwnCloudAccount(com.owncloud.android.lib.common.OwnCloudAccount) IOException(java.io.IOException) RegisterAccountDeviceForProxyOperation(com.owncloud.android.lib.resources.notifications.RegisterAccountDeviceForProxyOperation) PushConfigurationState(com.owncloud.android.datamodel.PushConfigurationState) OwnCloudClient(com.owncloud.android.lib.common.OwnCloudClient) PushResponse(com.owncloud.android.lib.resources.notifications.models.PushResponse)

Aggregations

ArbitraryDataProvider (com.owncloud.android.datamodel.ArbitraryDataProvider)26 Account (android.accounts.Account)14 Context (android.content.Context)8 OwnCloudAccount (com.owncloud.android.lib.common.OwnCloudAccount)8 IOException (java.io.IOException)8 File (java.io.File)6 Intent (android.content.Intent)5 View (android.view.View)4 PersistableBundleCompat (com.evernote.android.job.util.support.PersistableBundleCompat)4 FilesystemDataProvider (com.owncloud.android.datamodel.FilesystemDataProvider)4 RemoteOperationResult (com.owncloud.android.lib.common.operations.RemoteOperationResult)4 ContentResolver (android.content.ContentResolver)3 NonNull (android.support.annotation.NonNull)3 Gson (com.google.gson.Gson)3 PushConfigurationState (com.owncloud.android.datamodel.PushConfigurationState)3 AuthenticatorException (android.accounts.AuthenticatorException)2 OperationCanceledException (android.accounts.OperationCanceledException)2 Drawable (android.graphics.drawable.Drawable)2 Nullable (android.support.annotation.Nullable)2 RequiresApi (android.support.annotation.RequiresApi)2