public boolean pull() { // TODO Auto-generated method stub if (!isLinked()) return false; File file; FileOutputStream outputStream = null; try { Entry entry = mDBApi.metadata("/", 0, null, true, null); for (Entry e : entry.contents) { if (!e.isDir) { app.getGui().setStatus("Downloading..."); file = new File(NoteManager.defaultPath.concat(e.fileName())); outputStream = new FileOutputStream(file); DropboxFileInfo info = mDBApi.getFile("/".concat(e.fileName()), null, outputStream, null); app.getGui().setStatus("Downloaded ".concat(info.getMetadata().fileName())); outputStream.close(); } } return true; } catch (DropboxException e) { e.printStackTrace(); app.getGui().setStatus("Couldn't connect to server."); } catch (FileNotFoundException e) { e.printStackTrace(); app.getGui().setStatus("Files not found."); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); app.getGui().setStatus("IO errors."); } return false; }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // --------- auth ---------- // We create a new AuthSession so that we can use the Dropbox API. AndroidAuthSession session = buildSession(); mApi = new DropboxAPI<AndroidAuthSession>(session); // Basic Android widgets setContentView(R.layout.main); checkAppKeySetup(); if (mApi.getSession().isLinked() == false) { Toast.makeText(this, "starting auth", Toast.LENGTH_LONG).show(); mApi.getSession().startAuthentication(PhotoShareActivity.this); } else { // -------- upload ----------- uploadFiles(); } // Display the proper UI state if logged in or not // setLoggedIn(mApi.getSession().isLinked()); }
/* Dropbox account connection initialization */ private void linkDropbox() { if (mLoggedIn) { logOut(); } else { if (USE_OAUTH1) { mApi.getSession().startAuthentication(activity); } else { mApi.getSession().startOAuth2Authentication(activity); } } }
DropboxAPI<AndroidAuthSession> getAPI(Activity activity) { AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET); AndroidAuthSession session = new AndroidAuthSession(appKeys, AccessType.APP_FOLDER); DropboxAPI<AndroidAuthSession> mDBApi = new DropboxAPI<AndroidAuthSession>(session); AccessTokenPair token = getStoredKeys(); if (token != null) { mDBApi.getSession().setAccessTokenPair(token); } else { mDBApi.getSession().startAuthentication(activity); } return mDBApi; }
public void onResume() { super.onResume(); if (mDBApi.getSession().authenticationSuccessful()) { try { // Required to complete auth, sets the access token on the session mDBApi.getSession().finishAuthentication(); // tokens = mDBApi.getSession().getAccessTokenPair(); } catch (IllegalStateException e) { Log.i("DbAuthLog", "Error authenticating", e); } } }
private void visitEntry(final Entry entry, DropboxEntryVisitor visitor) { if (null != entry.contents) { logger.debug(entry.path + "contents size: " + entry.contents.size()); for (Entry child : entry.contents) { if (!child.isDeleted) { if (!child.isDir) { visitor.visitFile(child); } else { try { visitor.preVisitDirectory(child); } catch (IOException e) { logger.error(e.getMessage()); } try { Entry childWithContents = api.metadata( child.path, 0, MetaHandler.getHash(child.path), true, MetaHandler.getRev(child.path)); visitEntry(childWithContents, visitor); } catch (DropboxException e) { logger.error(e.getMessage()); } visitor.postVisitDirectory(child); } } } } }
@Override protected void onResume() { super.onResume(); Toast.makeText(this, "PhotoShareActivity.onResume", Toast.LENGTH_SHORT).show(); AndroidAuthSession session = mApi.getSession(); // The next part must be inserted in the onResume() method of the // activity from which session.startAuthentication() was called, so // that Dropbox authentication completes properly. if (session.authenticationSuccessful()) { try { // Mandatory call to complete the auth session.finishAuthentication(); // Store it locally in our app for later use TokenPair tokens = session.getAccessTokenPair(); storeKeys(tokens.key, tokens.secret); uploadFiles(); setLoggedIn(true); } catch (IllegalStateException e) { showToast("Couldn't authenticate with Dropbox:" + e.getLocalizedMessage()); Log.i(TAG, "Error authenticating", e); } } else { Toast.makeText(this, "PhotoShareActivity.onResume: failed to auth", Toast.LENGTH_LONG).show(); } }
@Override protected void onPostExecute(String s) { super.onPostExecute(s); progressDialog.dismiss(); api.getSession().unlink(); Toast.makeText(context, context.getString(R.string.dropbox_backup), Toast.LENGTH_LONG).show(); }
public void UnLink() { // Remove credentials from the session dropboxApi.getSession().unlink(); // Clear our stored keys clearKeys(); }
private void loadMetadata(DropboxFile file) { Log.d(TAG, "Loading metadata for " + file.getRemoteFile()); DropboxAPI.Entry metadata = null; try { metadata = dropboxApi.metadata(file.getRemoteFile(), 0, null, false, null); } catch (DropboxServerException se) { if (se.error == DropboxServerException._404_NOT_FOUND) { Log.d(TAG, "metadata NOT found! Returning NOT_FOUND status."); file.setStatus(DropboxFileStatus.NOT_FOUND); return; } throw new RemoteException("Server Exception: " + se.error + " " + se.reason, se); } catch (DropboxException e) { throw new RemoteException("Dropbox Exception: " + e.getMessage(), e); } Log.d(TAG, "Metadata retrieved. rev on Dropbox = " + metadata.rev); Log.d(TAG, "local rev = " + file.getOriginalRev()); file.setLoadedMetadata(metadata); if (metadata.rev.equals(file.getOriginalRev())) { // don't bother downloading if the rev is the same Log.d(TAG, "revs match. returning NOT_CHANGED status."); file.setStatus(DropboxFileStatus.NOT_CHANGED); } else if (metadata.isDeleted) { Log.d(TAG, "File marked as deleted on Dropbox! Returning NOT_FOUND status."); file.setStatus(DropboxFileStatus.NOT_FOUND); } else { Log.d(TAG, "revs don't match. returning FOUND status."); file.setStatus(DropboxFileStatus.FOUND); } }
public boolean push() { if (!isLinked()) return false; FileInputStream inputStream = null; try { app.getGui().setStatus("Uploading..."); File[] files = new File(NoteManager.defaultPath).listFiles(); for (int i = 0; i < files.length; i++) { inputStream = new FileInputStream(files[i]); mDBApi.putFileOverwrite( "/".concat(files[i].getName()), inputStream, files[i].length(), null); app.getGui().setStatus("Uploaded ".concat(files[i].getName())); inputStream.close(); } return true; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); app.getGui().setStatus("Files not found."); } catch (DropboxException e) { // TODO Auto-generated catch block e.printStackTrace(); app.getGui().setStatus("Couldn't connect to server."); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); app.getGui().setStatus("IO errors."); } return false; }
@Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_back_up, container, false); AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET); AndroidAuthSession session = new AndroidAuthSession(appKeys, ACCESS_TYPE); mDBApi = new DropboxAPI<AndroidAuthSession>(session); Button backUp = (Button) rootView.findViewById(R.id.btn_upload); Button restoreBackUp = (Button) rootView.findViewById(R.id.btn_download); backUp.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { doBackUp(v.getContext()); } }); restoreBackUp.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { restoreBackUp(v.getContext()); } }); // MyActivity below should be your activity class name mDBApi.getSession().startAuthentication(rootView.getContext()); return rootView; }
@Override protected void onResume() { super.onResume(); // Toast.makeText(ActivityTracksListView.this, "After onResume", Toast.LENGTH_SHORT).show(); if (dropboxAuthenticationTry) { AndroidAuthSession session = dropbox.getSession(); if (session.authenticationSuccessful()) { try { // Required to complete auth, sets the access token on the session session.finishAuthentication(); TokenPair tokens = session.getAccessTokenPair(); // String accessToken = dropbox.getSession().getOAuth2AccessToken(); SharedPreferences prefs = getSharedPreferences(DROPBOX_PREF, 0); SharedPreferences.Editor editor = prefs.edit(); editor.putString(APP_KEY, tokens.key); editor.putString(APP_SECRET, tokens.secret); editor.apply(); Toast.makeText( ActivityTracksListView.this, "Authentication successful", Toast.LENGTH_LONG) .show(); // dropboxLoggedIn = true; uploadToDropbox(); } catch (IllegalStateException e) { Log.i("DbAuthLog", "Error authenticating", e); Toast.makeText( getApplicationContext(), "Error during Dropbox authentication", Toast.LENGTH_SHORT) .show(); } } dropboxAuthenticationTry = false; } }
private void loadFile(DropboxFile file) { Log.d(TAG, "Downloading " + file.getRemoteFile() + " at rev = " + file.getLoadedMetadata().rev); File localFile = file.getLocalFile(); try { if (!localFile.exists()) { Util.createParentDirectory(localFile); localFile.createNewFile(); } } catch (IOException e) { throw new RemoteException("Failed to ensure that file exists", e); } FileOutputStream outputStream = null; try { outputStream = new FileOutputStream(localFile); } catch (FileNotFoundException e1) { throw new RemoteException("Failed to find file", e1); } try { dropboxApi.getFile(file.getRemoteFile(), file.getLoadedMetadata().rev, outputStream, null); outputStream.flush(); outputStream.close(); } catch (DropboxException e) { throw new RemoteException("Cannot get file from Dropbox", e); } catch (IOException e) { throw new RemoteException("Failed to find file", e); } Log.d(TAG, "Download successful. Returning status SUCCESS"); file.setStatus(DropboxFileStatus.SUCCESS); }
@Override public void onResume() { super.onResume(); // refresh login state when coming back to the fragment refreshLoginState(); // if already loggedin we don't need to continue if (authenticating) { // The next part must be inserted in the onResume() method of the // fragment from which session.startAuthentication() was called, so // that Dropbox authentication completes properly. AndroidAuthSession session = mApi.getSession(); if (session.authenticationSuccessful()) { authenticating = false; try { // Mandatory call to complete the auth session.finishAuthentication(); // Store it locally in the app for later use TokenPair tokens = session.getAccessTokenPair(); storeKeys(tokens.key, tokens.secret); // set the preference flag setLoggedin(true); getDropboxAccountInfo(); } catch (IllegalStateException e) { Toast.makeText(parentActivity, "Couldn't authenticate with Dropbox:", Toast.LENGTH_LONG) .show(); } } // end of if authentication successful } else { // refresh Menu refreshMenus(); } }
@Override protected Boolean doInBackground(Void... params) { try { FileOutputStream outputStream = new FileOutputStream(mFile); mApi.getFile( mFilePath, null, outputStream, new ProgressListener() { @Override public long progressInterval() { // Update the progress bar every half-second or so return 500; } @Override public void onProgress(long bytes, long total) { publishProgress(bytes, total); } }); return true; } catch (FileNotFoundException e) { mErrorMsg = "The file wasn't found"; } catch (DropboxException e) { mErrorMsg = "Unknown error"; } return false; }
private void uploadFile(String relPath, Path fullPath) throws DropboxException, IOException { if (!fullPath.toFile().exists()) return; /*if(api.metadata(relPath, 1, null, false, null).rev == MetaHandler.getRev(relPath)){ logger.debug("File "+relPath+" not changed"); return; }*/ VOSync.debug("Uploading " + relPath); String rev = MetaHandler.getRev(relPath); InputStream inp = new FileInputStream(fullPath.toFile()); Entry fileEntry = api.putFile(relPath, inp, fullPath.toFile().length(), rev, null); inp.close(); Path destFilePath = FileSystems.getDefault() .getPath(fullPath.toFile().getParentFile().getPath(), fileEntry.fileName()); MetaHandler.setFile(relPath, destFilePath.toFile(), fileEntry.rev); logger.debug(relPath + " put to db"); // if the file was renamed, move the file on disk and download the current from server if (!fileEntry.fileName().equals(fullPath.toFile().getName())) { logger.error(fileEntry.fileName() + " != " + fullPath.toFile().getName()); fullPath.toFile().renameTo(destFilePath.toFile()); } }
// Dropbox API public void logOut() { // Remove credentials from the session mApi.getSession().unlink(); // Clear our stored keys clearKeys(); // Change UI state to display logged out version setLoggedIn(false); }
private void syncStorage() { try { logger.debug("Synching storage."); final String rootDir = "/"; Entry folderEntry = api.metadata(rootDir, 0, MetaHandler.getHash(rootDir), true, MetaHandler.getRev(rootDir)); // TODO handle removed entries visitEntry( folderEntry, new DropboxEntryVisitor() { @Override public void preVisitDirectory(Entry entry) throws IOException { if (!MetaHandler.isStored(entry.path)) { logger.debug("Creating local dir: " + entry.path); Path filePath = FileSystems.getDefault().getPath(startDir.toString(), entry.path.substring(1)); WatchKey key = filePath .getParent() .register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); keys.remove(key); key.cancel(); filePath.toFile().mkdir(); key = filePath .getParent() .register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); keys.put(key, filePath.getParent()); MetaHandler.setFile(entry.path, filePath.toFile(), entry.rev); } } @Override public void visitFile(Entry entry) { if (!MetaHandler.isStored(entry.path)) downloadFile(entry.path); else if (!MetaHandler.isCurrent(entry.path, entry.rev)) { Path fullPath = FileSystems.getDefault().getPath(startDir.toString(), entry.path.substring(1)); try { logger.debug("Uploading file " + entry.path); uploadFile(entry.path, fullPath); } catch (Exception e) { logger.error("Error uploading file: " + e.getMessage()); } } } }); } catch (DropboxException ex) { logger.error("Error syching root dir: " + ex.getMessage()); } }
void finishAuthentication(DropboxAPI<AndroidAuthSession> mDBApi) { if (mDBApi.getSession().authenticationSuccessful()) { try { // MANDATORY call to complete auth. // Sets the access token on the session mDBApi.getSession().finishAuthentication(); AccessTokenPair tokens = mDBApi.getSession().getAccessTokenPair(); // Provide your own storeKeys to persist the access token pair // A typical way to store tokens is using SharedPreferences storeKeys(tokens.key, tokens.secret); Log.i("DbAuthLog", "Authenticated"); } catch (IllegalStateException e) { Log.i("DbAuthLog", "Error authenticating", e); } } }
@SuppressLint("ValidFragment") public DropboxFilePickerFragment(final DropboxAPI<AndroidAuthSession> api) { super(); if (api == null) { throw new NullPointerException("FileSystem may not be null"); } else if (!api.getSession().isLinked()) { throw new IllegalArgumentException("Must be linked with Dropbox"); } this.dbApi = api; }
public BufferedReader getRemoteFile(String filename) throws IOException { String filePath = this.remotePath + filename; try { DropboxInputStream is = dropboxApi.getFileStream(filePath, null); BufferedReader fileReader = new BufferedReader(new InputStreamReader(is)); return fileReader; } catch (DropboxUnlinkedException e) { throw new IOException("Dropbox Authentication Failed, re-run setup wizard"); } catch (DropboxException e) { throw new IOException("Fetching " + filename + ": " + e.toString()); } }
private void logOutDropbox() { // Remove credentials from the session mApi.getSession().unlink(); // Clear our stored keys clearKeys(); if (dataSourceNames != null) { dataSourceNames[0] = "Dropbox"; refreshMenus(); } authenticating = false; }
/** * This handles authentication if the user's token & secret are stored locally, so we don't have * to store user-name & password and re-send every time. */ private void connect() { AndroidAuthSession session = buildSession(); dropboxApi = new DropboxAPI<AndroidAuthSession>(session); if (!dropboxApi.getSession().isLinked()) { isLoggedIn = false; Log.d("MobileOrg", "Dropbox account was unlinked..."); // throw new IOException("Dropbox Authentication Failed, re-run setup wizard"); } else { isLoggedIn = true; } }
protected void onResume() { super.onResume(); if (mDBApi.getSession().authenticationSuccessful()) { try { // Required to complete auth, sets the access token on the session mDBApi.getSession().finishAuthentication(); AccessTokenPair accessToken = mDBApi.getSession().getAccessTokenPair(); Log.e("log_tag", "Accesstoken key : " + accessToken.key.toString()); Log.e("log_tag", "Accesstoken secret : " + accessToken.secret.toString()); SharedPreferences prefs = getSharedPreferences(ACCOUNT_PREFS_NAME, 0); Editor edit = prefs.edit(); edit.putString(ACCESS_KEY_NAME, accessToken.key); edit.putString(ACCESS_SECRET_NAME, accessToken.secret); edit.commit(); } catch (IllegalStateException e) { Log.i("DbAuthLog", "Error authenticating", e); } } }
public boolean FinishAuthorization() { AndroidAuthSession session = dropboxApi.getSession(); if (!session.isLinked() && session.authenticationSuccessful()) { // Mandatory call to complete the auth session.finishAuthentication(); // Store it locally in our app for later use TokenPair tokens = session.getAccessTokenPair(); storeKeys(tokens.key, tokens.secret); return true; } return false; }
@Override protected Void doInBackground(Void... params) { try { inputStream = new FileInputStream(file); DropboxAPI.Entry response = mDBApi.putFile(file.getName(), inputStream, file.length(), null, null); Log.d(log, "doInBackground() The uploaded file's rev is: " + response.rev); } catch (FileNotFoundException e) { e.printStackTrace(); Log.d(log, "doInBackground() FileNotFoundException " + e.toString()); } catch (DropboxException e) { e.printStackTrace(); Log.d(log, "doInBackground() DropboxException " + e.toString()); } return null; }
public void receiveTokenAndConnect() { // Dropbox API - recibe el token y se conecta AndroidAuthSession session = mApi.getSession(); if (session.authenticationSuccessful()) { try { // Mandatory call to complete the auth session.finishAuthentication(); // Store it locally in our app for later use TokenPair tokens = session.getAccessTokenPair(); storeKeys(tokens.key, tokens.secret); setLoggedIn(true); // showToast("Logueado bien" + tokens.key + " - " + tokens.secret); } catch (IllegalStateException e) { showToast("Couldn't authenticate with Dropbox:" + e.getLocalizedMessage()); Log.i(DropboxUtil.TAG, "Error authenticating", e); } } }
public String accountInfo() { // TODO Auto-generated method stub if (!isLinked()) return "You haven't been logged yet.\nPress Dropbox -> Login."; try { Account account = mDBApi.accountInfo(); StringBuilder user = new StringBuilder(account.displayName); user.append("\nCountry : "); user.append(account.country); user.append("\nUsage : "); user.append(account.quota); return user.toString(); } catch (DropboxException e) { // TODO Auto-generated catch block e.printStackTrace(); return null; } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); // Basic Android widgets checkAppKeySetup(); totalSize = (TextView) findViewById(R.id.totalSize); usedSize = (TextView) findViewById(R.id.usedSize); availableSize = (TextView) findViewById(R.id.availableSize); // Display the proper UI state if logged in or not setLoggedIn(mApi.getSession().isLinked()); }