use of com.owncloud.android.lib.common.OwnCloudClient in project android by nextcloud.
the class PushUtils method pushRegistrationToServer.
public static void pushRegistrationToServer(final UserAccountManager accountManager, final String token) {
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;
Gson gson = new Gson();
for (Account account : accountManager.getAccounts()) {
providerValue = arbitraryDataProvider.getValue(account.name, 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 client = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, context);
RemoteOperationResult remoteOperationResult = new RegisterAccountDeviceForNotificationsOperation(pushTokenHash, publicKey, context.getResources().getString(R.string.push_server_url)).execute(client);
if (remoteOperationResult.isSuccess()) {
PushResponse pushResponse = remoteOperationResult.getPushResponseData();
RemoteOperationResult resultProxy = new RegisterAccountDeviceForProxyOperation(context.getResources().getString(R.string.push_server_url), token, pushResponse.getDeviceIdentifier(), pushResponse.getSignature(), pushResponse.getPublicKey(), MainApp.getUserAgent()).run();
if (resultProxy.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, UserAccountManager.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);
}
}
}
}
}
use of com.owncloud.android.lib.common.OwnCloudClient in project android by nextcloud.
the class InputStreamBinder method processRequest.
private HttpMethodBase processRequest(final NextcloudRequest request, final InputStream requestBodyInputStream) throws UnsupportedOperationException, com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException, OperationCanceledException, AuthenticatorException, IOException {
Account account = accountManager.getAccountByName(request.getAccountName());
if (account == null) {
throw new IllegalStateException(EXCEPTION_ACCOUNT_NOT_FOUND);
}
// Validate token
if (!isValid(request)) {
throw new IllegalStateException(EXCEPTION_INVALID_TOKEN);
}
// Validate URL
if (request.getUrl().length() == 0 || request.getUrl().charAt(0) != PATH_SEPARATOR) {
throw new IllegalStateException(EXCEPTION_INVALID_REQUEST_URL, new IllegalStateException("URL need to start with a /"));
}
OwnCloudClientManager ownCloudClientManager = OwnCloudClientManagerFactory.getDefaultSingleton();
OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
OwnCloudClient client = ownCloudClientManager.getClientFor(ocAccount, context);
HttpMethodBase method = buildMethod(request, client.getBaseUri(), requestBodyInputStream);
if (request.getParameterV2() != null && !request.getParameterV2().isEmpty()) {
method.setQueryString(convertListToNVP(request.getParameterV2()));
} else {
method.setQueryString(convertMapToNVP(request.getParameter()));
}
method.addRequestHeader("OCS-APIREQUEST", "true");
for (Map.Entry<String, List<String>> header : request.getHeader().entrySet()) {
// https://stackoverflow.com/a/3097052
method.addRequestHeader(header.getKey(), TextUtils.join(",", header.getValue()));
if ("OCS-APIREQUEST".equalsIgnoreCase(header.getKey())) {
throw new IllegalStateException("The 'OCS-APIREQUEST' header will be automatically added by the Nextcloud SSO Library. " + "Please remove the header before making a request");
}
}
client.setFollowRedirects(request.isFollowRedirects());
int status = client.executeMethod(method);
// Check if status code is 2xx --> https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#2xx_Success
if (status >= HTTP_STATUS_CODE_OK && status < HTTP_STATUS_CODE_MULTIPLE_CHOICES) {
return method;
} else {
InputStream inputStream = method.getResponseBodyAsStream();
String total = "No response body";
// If response body is available
if (inputStream != null) {
total = inputStreamToString(inputStream);
Log_OC.e(TAG, total);
}
method.releaseConnection();
throw new IllegalStateException(EXCEPTION_HTTP_REQUEST_FAILED, new IllegalStateException(String.valueOf(status), new IllegalStateException(total)));
}
}
use of com.owncloud.android.lib.common.OwnCloudClient in project android by nextcloud.
the class ThumbnailsCacheManager method generateThumbnailFromOCFile.
public static void generateThumbnailFromOCFile(OCFile file, User user, Context context) {
int pxW;
int pxH;
pxW = pxH = getThumbnailDimension();
String imageKey = PREFIX_THUMBNAIL + file.getRemoteId();
GetMethod getMethod = null;
try {
Bitmap thumbnail = null;
OwnCloudClient client = mClient;
if (client == null) {
OwnCloudAccount ocAccount = user.toOwnCloudAccount();
client = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, context);
}
String uri = client.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" + pxW + "/" + pxH + Uri.encode(file.getRemotePath(), "/");
Log_OC.d(TAG, "generate thumbnail: " + file.getFileName() + " URI: " + uri);
getMethod = new GetMethod(uri);
getMethod.setRequestHeader("Cookie", "nc_sameSiteCookielax=true;nc_sameSiteCookiestrict=true");
getMethod.setRequestHeader(RemoteOperation.OCS_API_HEADER, RemoteOperation.OCS_API_HEADER_VALUE);
int status = client.executeMethod(getMethod);
if (status == HttpStatus.SC_OK) {
InputStream inputStream = getMethod.getResponseBodyAsStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
thumbnail = ThumbnailUtils.extractThumbnail(bitmap, pxW, pxH);
} else {
client.exhaustResponse(getMethod.getResponseBodyAsStream());
}
// Add thumbnail to cache
if (thumbnail != null) {
// Handle PNG
if (PNG_MIMETYPE.equalsIgnoreCase(file.getMimeType())) {
thumbnail = handlePNG(thumbnail, pxW, pxH);
}
Log_OC.d(TAG, "add thumbnail to cache: " + file.getFileName());
addBitmapToCache(imageKey, thumbnail);
}
} catch (Exception e) {
Log_OC.d(TAG, e.getMessage(), e);
} finally {
if (getMethod != null) {
getMethod.releaseConnection();
}
}
}
use of com.owncloud.android.lib.common.OwnCloudClient in project android by nextcloud.
the class SyncFolderHandler method doOperation.
/**
* Performs the next operation in the queue
*/
private void doOperation(Account account, String remotePath) {
mCurrentSyncOperation = mPendingOperations.get(account.name, remotePath);
if (mCurrentSyncOperation != null) {
RemoteOperationResult result;
try {
if (mCurrentAccount == null || !mCurrentAccount.equals(account)) {
mCurrentAccount = account;
}
// always get client from client manager, to get fresh credentials in case of update
OwnCloudAccount ocAccount = new OwnCloudAccount(account, mService);
OwnCloudClient mOwnCloudClient = OwnCloudClientManagerFactory.getDefaultSingleton().getClientFor(ocAccount, mService);
result = mCurrentSyncOperation.execute(mOwnCloudClient);
sendBroadcastFinishedSyncFolder(account, remotePath, result.isSuccess());
mService.dispatchResultToOperationListeners(mCurrentSyncOperation, result);
} catch (AccountsException | IOException e) {
sendBroadcastFinishedSyncFolder(account, remotePath, false);
mService.dispatchResultToOperationListeners(mCurrentSyncOperation, new RemoteOperationResult(e));
Log_OC.e(TAG, "Error while trying to get authorization", e);
} finally {
mPendingOperations.removePayload(account.name, remotePath);
}
}
}
use of com.owncloud.android.lib.common.OwnCloudClient in project android by nextcloud.
the class DocumentsStorageProvider method createFile.
private String createFile(Document targetFolder, String displayName, String mimeType) throws FileNotFoundException {
User user = targetFolder.getUser();
// create dummy file
File tempDir = new File(FileStorageUtils.getTemporalPath(user.getAccountName()));
if (!tempDir.exists() && !tempDir.mkdirs()) {
throw new FileNotFoundException("Temp folder could not be created: " + tempDir.getAbsolutePath());
}
File emptyFile = new File(tempDir, displayName);
if (emptyFile.exists() && !emptyFile.delete()) {
throw new FileNotFoundException("Previous file could not be deleted");
}
try {
if (!emptyFile.createNewFile()) {
throw new FileNotFoundException("File could not be created");
}
} catch (IOException e) {
throw getFileNotFoundExceptionWithCause("File could not be created", e);
}
String newFilePath = targetFolder.getRemotePath() + displayName;
// FIXME we need to update the mimeType somewhere else as well
// perform the upload, no need for chunked operation as we have a empty file
OwnCloudClient client = targetFolder.getClient();
RemoteOperationResult result = new UploadFileRemoteOperation(emptyFile.getAbsolutePath(), newFilePath, mimeType, "", String.valueOf(System.currentTimeMillis() / 1000), FileUtil.getCreationTimestamp(emptyFile), false).execute(client);
if (!result.isSuccess()) {
Log_OC.e(TAG, result.toString());
throw new FileNotFoundException("Failed to upload document with path " + newFilePath);
}
Context context = getNonNullContext();
RemoteOperationResult updateParent = new RefreshFolderOperation(targetFolder.getFile(), System.currentTimeMillis(), false, false, true, targetFolder.getStorageManager(), user, context).execute(client);
if (!updateParent.isSuccess()) {
Log_OC.e(TAG, updateParent.toString());
throw new FileNotFoundException("Failed to create document with documentId " + targetFolder.getDocumentId());
}
Document newFile = new Document(targetFolder.getStorageManager(), newFilePath);
context.getContentResolver().notifyChange(toNotifyUri(targetFolder), null, false);
return newFile.getDocumentId();
}
Aggregations