Changed the synchronization process to limit the number and type of failures supporte...
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / FileDisplayActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package com.owncloud.android.ui.activity;
20
21 import java.io.File;
22
23 import android.accounts.Account;
24 import android.app.AlertDialog;
25 import android.app.ProgressDialog;
26 import android.app.AlertDialog.Builder;
27 import android.app.Dialog;
28 import android.content.BroadcastReceiver;
29 import android.content.ComponentName;
30 import android.content.ContentResolver;
31 import android.content.Context;
32 import android.content.DialogInterface;
33 import android.content.DialogInterface.OnClickListener;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.content.ServiceConnection;
37 import android.content.SharedPreferences;
38 import android.content.pm.PackageInfo;
39 import android.content.pm.PackageManager.NameNotFoundException;
40 import android.content.res.Resources.NotFoundException;
41 import android.database.Cursor;
42 import android.net.Uri;
43 import android.os.Bundle;
44 import android.os.Handler;
45 import android.os.IBinder;
46 import android.preference.PreferenceManager;
47 import android.provider.MediaStore;
48 import android.support.v4.app.FragmentTransaction;
49 import android.util.Log;
50 import android.view.View;
51 import android.view.ViewGroup;
52 import android.widget.ArrayAdapter;
53 import android.widget.EditText;
54 import android.widget.TextView;
55 import android.widget.Toast;
56
57 import com.actionbarsherlock.app.ActionBar;
58 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
59 import com.actionbarsherlock.app.SherlockFragmentActivity;
60 import com.actionbarsherlock.view.Menu;
61 import com.actionbarsherlock.view.MenuInflater;
62 import com.actionbarsherlock.view.MenuItem;
63 import com.actionbarsherlock.view.Window;
64 import com.owncloud.android.AccountUtils;
65 import com.owncloud.android.authenticator.AccountAuthenticator;
66 import com.owncloud.android.datamodel.DataStorageManager;
67 import com.owncloud.android.datamodel.FileDataStorageManager;
68 import com.owncloud.android.datamodel.OCFile;
69 import com.owncloud.android.files.services.FileDownloader;
70 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
71 import com.owncloud.android.files.services.FileUploader;
72 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
73 import com.owncloud.android.network.OwnCloudClientUtils;
74 import com.owncloud.android.operations.RemoteOperationResult;
75 import com.owncloud.android.syncadapter.FileSyncService;
76 import com.owncloud.android.ui.dialog.SslValidatorDialog;
77 import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
78 import com.owncloud.android.ui.fragment.FileDetailFragment;
79 import com.owncloud.android.ui.fragment.OCFileListFragment;
80
81 import com.owncloud.android.R;
82 import eu.alefzero.webdav.WebdavClient;
83
84 /**
85 * Displays, what files the user has available in his ownCloud.
86 *
87 * @author Bartek Przybylski
88 *
89 */
90
91 public class FileDisplayActivity extends SherlockFragmentActivity implements
92 OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener, OnSslValidatorListener {
93
94 private ArrayAdapter<String> mDirectories;
95 private OCFile mCurrentDir = null;
96 private OCFile mCurrentFile = null;
97
98 private DataStorageManager mStorageManager;
99 private SyncBroadcastReceiver mSyncBroadcastReceiver;
100 private UploadFinishReceiver mUploadFinishReceiver;
101 private DownloadFinishReceiver mDownloadFinishReceiver;
102 private FileDownloaderBinder mDownloaderBinder = null;
103 private FileUploaderBinder mUploaderBinder = null;
104 private ServiceConnection mDownloadConnection = null, mUploadConnection = null;
105 private RemoteOperationResult mLastSslUntrustedServerResult = null;
106
107 private OCFileListFragment mFileList;
108
109 private boolean mDualPane;
110
111 private static final int DIALOG_SETUP_ACCOUNT = 0;
112 private static final int DIALOG_CREATE_DIR = 1;
113 private static final int DIALOG_ABOUT_APP = 2;
114 public static final int DIALOG_SHORT_WAIT = 3;
115 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 4;
116 private static final int DIALOG_SSL_VALIDATOR = 5;
117 private static final int DIALOG_CERT_NOT_SAVED = 6;
118
119
120 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
121 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
122
123 private static final String TAG = "FileDisplayActivity";
124
125 @Override
126 public void onCreate(Bundle savedInstanceState) {
127 Log.d(getClass().toString(), "onCreate() start");
128 super.onCreate(savedInstanceState);
129
130 /// Load of parameters from received intent
131 mCurrentDir = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE); // no check necessary, mCurrenDir == null if the parameter is not in the intent
132 Account account = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_ACCOUNT);
133 if (account != null)
134 AccountUtils.setCurrentOwnCloudAccount(this, account.name);
135
136 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
137 if(savedInstanceState != null) {
138 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
139 mCurrentDir = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
140 }
141
142 if (!AccountUtils.accountsAreSetup(this)) {
143 /// no account available: FORCE ACCOUNT CREATION
144 mStorageManager = null;
145 createFirstAccount();
146
147 } else { /// at least an account is available
148
149 initDataFromCurrentAccount(); // it checks mCurrentDir and mCurrentFile with the current account
150
151 }
152
153 mUploadConnection = new ListServiceConnection();
154 mDownloadConnection = new ListServiceConnection();
155 bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
156 bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
157
158 // PIN CODE request ; best location is to decide, let's try this first
159 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
160 requestPinCode();
161 }
162
163 // file observer
164 /*Intent observer_intent = new Intent(this, FileObserverService.class);
165 observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
166 startService(observer_intent);
167 */
168
169 /// USER INTERFACE
170 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
171
172 // Drop-down navigation
173 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
174 OCFile currFile = mCurrentDir;
175 while(currFile != null && currFile.getFileName() != OCFile.PATH_SEPARATOR) {
176 mDirectories.add(currFile.getFileName());
177 currFile = mStorageManager.getFileById(currFile.getParentId());
178 }
179 mDirectories.add(OCFile.PATH_SEPARATOR);
180
181 // Inflate and set the layout view
182 setContentView(R.layout.files);
183 mFileList = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
184 mDualPane = (findViewById(R.id.file_details_container) != null);
185 if (mDualPane) {
186 initFileDetailsInDualPane();
187 }
188
189 // Action bar setup
190 ActionBar actionBar = getSupportActionBar();
191 actionBar.setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
192 actionBar.setDisplayHomeAsUpEnabled(mCurrentDir != null && mCurrentDir.getParentId() != 0);
193 actionBar.setDisplayShowTitleEnabled(false);
194 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
195 actionBar.setListNavigationCallbacks(mDirectories, this);
196 setSupportProgressBarIndeterminateVisibility(false); // always AFTER setContentView(...) ; to workaround bug in its implementation
197
198 Log.d(getClass().toString(), "onCreate() end");
199 }
200
201
202 /**
203 * Launches the account creation activity. To use when no ownCloud account is available
204 */
205 private void createFirstAccount() {
206 Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
207 intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
208 startActivity(intent); // the new activity won't be created until this.onStart() and this.onResume() are finished;
209 }
210
211
212 /**
213 * Load of state dependent of the existence of an ownCloud account
214 */
215 private void initDataFromCurrentAccount() {
216 /// Storage manager initialization - access to local database
217 mStorageManager = new FileDataStorageManager(
218 AccountUtils.getCurrentOwnCloudAccount(this),
219 getContentResolver());
220
221 /// Check if mCurrentDir is a directory
222 if(mCurrentDir != null && !mCurrentDir.isDirectory()) {
223 mCurrentFile = mCurrentDir;
224 mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());
225 }
226
227 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
228 if (mCurrentDir != null) {
229 mCurrentDir = mStorageManager.getFileByPath(mCurrentDir.getRemotePath()); // mCurrentDir == null if it is not in the current account
230 }
231 if (mCurrentFile != null) {
232 if (mCurrentFile.fileExists()) {
233 mCurrentFile = mStorageManager.getFileByPath(mCurrentFile.getRemotePath()); // mCurrentFile == null if it is not in the current account
234 } // else : keep mCurrentFile with the received value; this is currently the case of an upload in progress, when the user presses the status notification in a landscape tablet
235 }
236
237 /// Default to root if mCurrentDir was not found
238 if (mCurrentDir == null) {
239 mCurrentDir = mStorageManager.getFileByPath("/"); // will be NULL if the database was never synchronized
240 }
241 }
242
243
244 private void initFileDetailsInDualPane() {
245 if (mDualPane && getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG) == null) {
246 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
247 if (mCurrentFile != null) {
248 transaction.replace(R.id.file_details_container, new FileDetailFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG); // empty FileDetailFragment
249 mCurrentFile = null;
250 } else {
251 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
252 }
253 transaction.commit();
254 }
255 }
256
257
258 @Override
259 public void onDestroy() {
260 super.onDestroy();
261 if (mDownloadConnection != null)
262 unbindService(mDownloadConnection);
263 if (mUploadConnection != null)
264 unbindService(mUploadConnection);
265 }
266
267
268 @Override
269 public boolean onCreateOptionsMenu(Menu menu) {
270 MenuInflater inflater = getSherlock().getMenuInflater();
271 inflater.inflate(R.menu.menu, menu);
272 return true;
273 }
274
275 @Override
276 public boolean onOptionsItemSelected(MenuItem item) {
277 boolean retval = true;
278 switch (item.getItemId()) {
279 case R.id.createDirectoryItem: {
280 showDialog(DIALOG_CREATE_DIR);
281 break;
282 }
283 case R.id.startSync: {
284 startSynchronization();
285 break;
286 }
287 case R.id.action_upload: {
288 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
289 break;
290 }
291 case R.id.action_settings: {
292 Intent settingsIntent = new Intent(this, Preferences.class);
293 startActivity(settingsIntent);
294 break;
295 }
296 case R.id.about_app : {
297 showDialog(DIALOG_ABOUT_APP);
298 break;
299 }
300 case android.R.id.home: {
301 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
302 onBackPressed();
303 }
304 break;
305 }
306 default:
307 retval = false;
308 }
309 return retval;
310 }
311
312 private void startSynchronization() {
313 ContentResolver.cancelSync(null, AccountAuthenticator.AUTH_TOKEN_TYPE); // cancel the current synchronizations of any ownCloud account
314 Bundle bundle = new Bundle();
315 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
316 ContentResolver.requestSync(
317 AccountUtils.getCurrentOwnCloudAccount(this),
318 AccountAuthenticator.AUTH_TOKEN_TYPE, bundle);
319 }
320
321
322 @Override
323 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
324 int i = itemPosition;
325 while (i-- != 0) {
326 onBackPressed();
327 }
328 // the next operation triggers a new call to this method, but it's necessary to
329 // ensure that the name exposed in the action bar is the current directory when the
330 // user selected it in the navigation list
331 if (itemPosition != 0)
332 getSupportActionBar().setSelectedNavigationItem(0);
333 return true;
334 }
335
336 /**
337 * Called, when the user selected something for uploading
338 */
339 public void onActivityResult(int requestCode, int resultCode, Intent data) {
340
341 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && resultCode == RESULT_OK) {
342 requestSimpleUpload(data);
343
344 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && resultCode == RESULT_OK) {
345 requestMultipleUpload(data);
346
347 }
348 }
349
350 private void requestMultipleUpload(Intent data) {
351 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
352 if (filePaths != null) {
353 String[] remotePaths = new String[filePaths.length];
354 String remotePathBase = "";
355 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
356 remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
357 }
358 if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
359 remotePathBase += OCFile.PATH_SEPARATOR;
360 for (int j = 0; j< remotePaths.length; j++) {
361 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
362 }
363
364 Intent i = new Intent(this, FileUploader.class);
365 i.putExtra(FileUploader.KEY_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
366 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
367 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
368 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
369 startService(i);
370
371 } else {
372 Log.d("FileDisplay", "User clicked on 'Update' with no selection");
373 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
374 t.show();
375 return;
376 }
377 }
378
379
380 private void requestSimpleUpload(Intent data) {
381 String filepath = null;
382 try {
383 Uri selectedImageUri = data.getData();
384
385 String filemanagerstring = selectedImageUri.getPath();
386 String selectedImagePath = getPath(selectedImageUri);
387
388 if (selectedImagePath != null)
389 filepath = selectedImagePath;
390 else
391 filepath = filemanagerstring;
392
393 } catch (Exception e) {
394 Log.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
395 e.printStackTrace();
396
397 } finally {
398 if (filepath == null) {
399 Log.e("FileDisplay", "Couldnt resolve path to file");
400 Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
401 t.show();
402 return;
403 }
404 }
405
406 Intent i = new Intent(this, FileUploader.class);
407 i.putExtra(FileUploader.KEY_ACCOUNT,
408 AccountUtils.getCurrentOwnCloudAccount(this));
409 String remotepath = new String();
410 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
411 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
412 }
413 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
414 remotepath += OCFile.PATH_SEPARATOR;
415 remotepath += new File(filepath).getName();
416
417 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
418 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
419 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
420 startService(i);
421 }
422
423
424 @Override
425 public void onBackPressed() {
426 if (mDirectories.getCount() <= 1) {
427 finish();
428 return;
429 }
430 popDirname();
431 mFileList.onNavigateUp();
432 mCurrentDir = mFileList.getCurrentFile();
433
434 if (mDualPane) {
435 // Resets the FileDetailsFragment on Tablets so that it always displays
436 FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
437 if (fileDetails != null && !fileDetails.isEmpty()) {
438 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
439 transaction.remove(fileDetails);
440 transaction.add(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG);
441 transaction.commit();
442 }
443 }
444
445 if(mCurrentDir.getParentId() == 0){
446 ActionBar actionBar = getSupportActionBar();
447 actionBar.setDisplayHomeAsUpEnabled(false);
448 }
449 }
450
451 @Override
452 protected void onSaveInstanceState(Bundle outState) {
453 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
454 Log.d(getClass().toString(), "onSaveInstanceState() start");
455 super.onSaveInstanceState(outState);
456 outState.putParcelable(FileDetailFragment.EXTRA_FILE, mCurrentDir);
457 if (mDualPane) {
458 FileDetailFragment fragment = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
459 if (fragment != null) {
460 OCFile file = fragment.getDisplayedFile();
461 if (file != null) {
462 outState.putParcelable(FileDetailFragment.EXTRA_FILE, file);
463 }
464 }
465 }
466 Log.d(getClass().toString(), "onSaveInstanceState() end");
467 }
468
469 @Override
470 protected void onResume() {
471 Log.d(getClass().toString(), "onResume() start");
472 super.onResume();
473
474 if (AccountUtils.accountsAreSetup(this)) {
475
476 if (mStorageManager == null) {
477 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
478 initDataFromCurrentAccount();
479 if (mDualPane) {
480 initFileDetailsInDualPane();
481 }
482 }
483
484 // Listen for sync messages
485 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
486 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
487 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
488
489 // Listen for upload messages
490 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
491 mUploadFinishReceiver = new UploadFinishReceiver();
492 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
493
494 // Listen for download messages
495 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
496 mDownloadFinishReceiver = new DownloadFinishReceiver();
497 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
498
499 // List current directory
500 mFileList.listDirectory(mCurrentDir); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
501
502 } else {
503
504 mStorageManager = null; // an invalid object will be there if all the ownCloud accounts are removed
505 showDialog(DIALOG_SETUP_ACCOUNT);
506
507 }
508 Log.d(getClass().toString(), "onResume() end");
509 }
510
511
512 @Override
513 protected void onPause() {
514 Log.d(getClass().toString(), "onPause() start");
515 super.onPause();
516 if (mSyncBroadcastReceiver != null) {
517 unregisterReceiver(mSyncBroadcastReceiver);
518 mSyncBroadcastReceiver = null;
519 }
520 if (mUploadFinishReceiver != null) {
521 unregisterReceiver(mUploadFinishReceiver);
522 mUploadFinishReceiver = null;
523 }
524 if (mDownloadFinishReceiver != null) {
525 unregisterReceiver(mDownloadFinishReceiver);
526 mDownloadFinishReceiver = null;
527 }
528 if (!AccountUtils.accountsAreSetup(this)) {
529 dismissDialog(DIALOG_SETUP_ACCOUNT);
530 }
531
532 Log.d(getClass().toString(), "onPause() end");
533 }
534
535
536 @Override
537 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
538 if (id == DIALOG_SSL_VALIDATOR && mLastSslUntrustedServerResult != null) {
539 ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
540 }
541 }
542
543
544 @Override
545 protected Dialog onCreateDialog(int id) {
546 Dialog dialog = null;
547 AlertDialog.Builder builder;
548 switch (id) {
549 case DIALOG_SETUP_ACCOUNT: {
550 builder = new AlertDialog.Builder(this);
551 builder.setTitle(R.string.main_tit_accsetup);
552 builder.setMessage(R.string.main_wrn_accsetup);
553 builder.setCancelable(false);
554 builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
555 public void onClick(DialogInterface dialog, int which) {
556 createFirstAccount();
557 dialog.dismiss();
558 }
559 });
560 builder.setNegativeButton(R.string.common_exit, new OnClickListener() {
561 public void onClick(DialogInterface dialog, int which) {
562 dialog.dismiss();
563 finish();
564 }
565 });
566 //builder.setNegativeButton(android.R.string.cancel, this);
567 dialog = builder.create();
568 break;
569 }
570 case DIALOG_ABOUT_APP: {
571 builder = new AlertDialog.Builder(this);
572 builder.setTitle(getString(R.string.about_title));
573 PackageInfo pkg;
574 try {
575 pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
576 builder.setMessage(String.format(getString(R.string.about_message), pkg.versionName));
577 builder.setIcon(android.R.drawable.ic_menu_info_details);
578 dialog = builder.create();
579 } catch (NameNotFoundException e) {
580 builder = null;
581 dialog = null;
582 Log.e(TAG, "Error while showing about dialog", e);
583 }
584 break;
585 }
586 case DIALOG_CREATE_DIR: {
587 builder = new Builder(this);
588 final EditText dirNameInput = new EditText(getBaseContext());
589 builder.setView(dirNameInput);
590 builder.setTitle(R.string.uploader_info_dirname);
591 int typed_color = getResources().getColor(R.color.setup_text_typed);
592 dirNameInput.setTextColor(typed_color);
593 builder.setPositiveButton(android.R.string.ok,
594 new OnClickListener() {
595 public void onClick(DialogInterface dialog, int which) {
596 String directoryName = dirNameInput.getText().toString();
597 if (directoryName.trim().length() == 0) {
598 dialog.cancel();
599 return;
600 }
601
602 // Figure out the path where the dir needs to be created
603 String path;
604 if (mCurrentDir == null) {
605 // this is just a patch; we should ensure that mCurrentDir never is null
606 if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {
607 OCFile file = new OCFile(OCFile.PATH_SEPARATOR);
608 mStorageManager.saveFile(file);
609 }
610 mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
611 }
612 path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
613
614 // Create directory
615 path += directoryName + OCFile.PATH_SEPARATOR;
616 Thread thread = new Thread(new DirectoryCreator(path, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this), new Handler()));
617 thread.start();
618
619 dialog.dismiss();
620
621 showDialog(DIALOG_SHORT_WAIT);
622 }
623 });
624 builder.setNegativeButton(R.string.common_cancel,
625 new OnClickListener() {
626 public void onClick(DialogInterface dialog, int which) {
627 dialog.cancel();
628 }
629 });
630 dialog = builder.create();
631 break;
632 }
633 case DIALOG_SHORT_WAIT: {
634 ProgressDialog working_dialog = new ProgressDialog(this);
635 working_dialog.setMessage(getResources().getString(
636 R.string.wait_a_moment));
637 working_dialog.setIndeterminate(true);
638 working_dialog.setCancelable(false);
639 dialog = working_dialog;
640 break;
641 }
642 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
643 final String [] items = { getString(R.string.actionbar_upload_files),
644 getString(R.string.actionbar_upload_from_apps) };
645 builder = new AlertDialog.Builder(this);
646 builder.setTitle(R.string.actionbar_upload);
647 builder.setItems(items, new DialogInterface.OnClickListener() {
648 public void onClick(DialogInterface dialog, int item) {
649 if (item == 0) {
650 //if (!mDualPane) {
651 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
652 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
653 //} else {
654 // TODO create and handle new fragment LocalFileListFragment
655 //}
656 } else if (item == 1) {
657 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
658 action = action.setType("*/*")
659 .addCategory(Intent.CATEGORY_OPENABLE);
660 startActivityForResult(
661 Intent.createChooser(action, getString(R.string.upload_chooser_title)),
662 ACTION_SELECT_CONTENT_FROM_APPS);
663 }
664 }
665 });
666 dialog = builder.create();
667 break;
668 }
669 case DIALOG_SSL_VALIDATOR: {
670 dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
671 break;
672 }
673 case DIALOG_CERT_NOT_SAVED: {
674 builder = new AlertDialog.Builder(this);
675 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
676 builder.setCancelable(false);
677 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
678 @Override
679 public void onClick(DialogInterface dialog, int which) {
680 dialog.dismiss();
681 };
682 });
683 dialog = builder.create();
684 break;
685 }
686 default:
687 dialog = null;
688 }
689
690 return dialog;
691 }
692
693
694 /**
695 * Translates a content URI of an image to a physical path
696 * on the disk
697 * @param uri The URI to resolve
698 * @return The path to the image or null if it could not be found
699 */
700 public String getPath(Uri uri) {
701 String[] projection = { MediaStore.Images.Media.DATA };
702 Cursor cursor = managedQuery(uri, projection, null, null, null);
703 if (cursor != null) {
704 int column_index = cursor
705 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
706 cursor.moveToFirst();
707 return cursor.getString(column_index);
708 }
709 return null;
710 }
711
712 /**
713 * Pushes a directory to the drop down list
714 * @param directory to push
715 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
716 */
717 public void pushDirname(OCFile directory) {
718 if(!directory.isDirectory()){
719 throw new IllegalArgumentException("Only directories may be pushed!");
720 }
721 mDirectories.insert(directory.getFileName(), 0);
722 mCurrentDir = directory;
723 }
724
725 /**
726 * Pops a directory name from the drop down list
727 * @return True, unless the stack is empty
728 */
729 public boolean popDirname() {
730 mDirectories.remove(mDirectories.getItem(0));
731 return !mDirectories.isEmpty();
732 }
733
734 private class DirectoryCreator implements Runnable {
735 private String mTargetPath;
736 private Account mAccount;
737 private Handler mHandler;
738
739 public DirectoryCreator(String targetPath, Account account, Handler handler) {
740 mTargetPath = targetPath;
741 mAccount = account;
742 mHandler = handler;
743 }
744
745 @Override
746 public void run() {
747 WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
748 boolean created = wdc.createDirectory(mTargetPath);
749 if (created) {
750 mHandler.post(new Runnable() {
751 @Override
752 public void run() {
753 dismissDialog(DIALOG_SHORT_WAIT);
754
755 // Save new directory in local database
756 OCFile newDir = new OCFile(mTargetPath);
757 newDir.setMimetype("DIR");
758 newDir.setParentId(mCurrentDir.getFileId());
759 mStorageManager.saveFile(newDir);
760
761 // Display the new folder right away
762 mFileList.listDirectory();
763 }
764 });
765
766 } else {
767 mHandler.post(new Runnable() {
768 @Override
769 public void run() {
770 dismissDialog(DIALOG_SHORT_WAIT);
771 try {
772 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
773 msg.show();
774
775 } catch (NotFoundException e) {
776 Log.e(TAG, "Error while trying to show fail message " , e);
777 }
778 }
779 });
780 }
781 }
782
783 }
784
785 // Custom array adapter to override text colors
786 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
787
788 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
789 super(ctx, view);
790 }
791
792 public View getView(int position, View convertView, ViewGroup parent) {
793 View v = super.getView(position, convertView, parent);
794
795 ((TextView) v).setTextColor(getResources().getColorStateList(
796 android.R.color.white));
797 return v;
798 }
799
800 public View getDropDownView(int position, View convertView,
801 ViewGroup parent) {
802 View v = super.getDropDownView(position, convertView, parent);
803
804 ((TextView) v).setTextColor(getResources().getColorStateList(
805 android.R.color.white));
806
807 return v;
808 }
809
810 }
811
812 private class SyncBroadcastReceiver extends BroadcastReceiver {
813
814 /**
815 * {@link BroadcastReceiver} to enable syncing feedback in UI
816 */
817 @Override
818 public void onReceive(Context context, Intent intent) {
819 boolean inProgress = intent.getBooleanExtra(
820 FileSyncService.IN_PROGRESS, false);
821 String accountName = intent
822 .getStringExtra(FileSyncService.ACCOUNT_NAME);
823
824 Log.d("FileDisplay", "sync of account " + accountName
825 + " is in_progress: " + inProgress);
826
827 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name)) {
828
829 String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
830
831 boolean fillBlankRoot = false;
832 if (mCurrentDir == null) {
833 mCurrentDir = mStorageManager.getFileByPath("/");
834 fillBlankRoot = (mCurrentDir != null);
835 }
836
837 if ((synchFolderRemotePath != null && mCurrentDir != null && (mCurrentDir.getRemotePath().equals(synchFolderRemotePath)))
838 || fillBlankRoot ) {
839 if (!fillBlankRoot)
840 mCurrentDir = getStorageManager().getFileByPath(synchFolderRemotePath);
841 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager()
842 .findFragmentById(R.id.fileList);
843 if (fileListFragment != null) {
844 fileListFragment.listDirectory(mCurrentDir);
845 }
846 }
847
848 setSupportProgressBarIndeterminateVisibility(inProgress);
849
850 }
851
852 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncService.SYNC_RESULT);
853 if (synchResult != null) {
854 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
855 mLastSslUntrustedServerResult = synchResult;
856 showDialog(DIALOG_SSL_VALIDATOR);
857 }
858 }
859 }
860 }
861
862
863 private class UploadFinishReceiver extends BroadcastReceiver {
864 /**
865 * Once the file upload has finished -> update view
866 * @author David A. Velasco
867 * {@link BroadcastReceiver} to enable upload feedback in UI
868 */
869 @Override
870 public void onReceive(Context context, Intent intent) {
871 long parentDirId = intent.getLongExtra(FileUploader.EXTRA_PARENT_DIR_ID, -1);
872 OCFile parentDir = mStorageManager.getFileById(parentDirId);
873 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
874
875 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&
876 parentDir != null &&
877 ( (mCurrentDir == null && parentDir.getFileName().equals("/")) ||
878 parentDir.equals(mCurrentDir)
879 )
880 ) {
881 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
882 if (fileListFragment != null) {
883 fileListFragment.listDirectory();
884 }
885 }
886 }
887
888 }
889
890
891 /**
892 * Once the file download has finished -> update view
893 */
894 private class DownloadFinishReceiver extends BroadcastReceiver {
895 @Override
896 public void onReceive(Context context, Intent intent) {
897 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
898 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
899
900 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&
901 mCurrentDir != null && mCurrentDir.getFileId() == mStorageManager.getFileByPath(downloadedRemotePath).getParentId()) {
902 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
903 if (fileListFragment != null) {
904 fileListFragment.listDirectory();
905 }
906 }
907 }
908 }
909
910
911
912
913 /**
914 * {@inheritDoc}
915 */
916 @Override
917 public DataStorageManager getStorageManager() {
918 return mStorageManager;
919 }
920
921
922 /**
923 * {@inheritDoc}
924 */
925 @Override
926 public void onDirectoryClick(OCFile directory) {
927 pushDirname(directory);
928 ActionBar actionBar = getSupportActionBar();
929 actionBar.setDisplayHomeAsUpEnabled(true);
930
931 if (mDualPane) {
932 // Resets the FileDetailsFragment on Tablets so that it always displays
933 FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
934 if (fileDetails != null && !fileDetails.isEmpty()) {
935 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
936 transaction.remove(fileDetails);
937 transaction.add(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG);
938 transaction.commit();
939 }
940 }
941 }
942
943
944 /**
945 * {@inheritDoc}
946 */
947 @Override
948 public void onFileClick(OCFile file) {
949
950 // If we are on a large device -> update fragment
951 if (mDualPane) {
952 // buttons in the details view are problematic when trying to reuse an existing fragment; create always a new one solves some of them, BUT no all; downloads are 'dangerous'
953 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
954 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
955 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
956 transaction.commit();
957
958 } else { // small or medium screen device -> new Activity
959 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
960 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
961 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
962 startActivity(showDetailsIntent);
963 }
964 }
965
966
967 /**
968 * {@inheritDoc}
969 */
970 @Override
971 public OCFile getInitialDirectory() {
972 return mCurrentDir;
973 }
974
975
976 /**
977 * {@inheritDoc}
978 */
979 @Override
980 public void onFileStateChanged() {
981 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
982 if (fileListFragment != null) {
983 fileListFragment.listDirectory();
984 }
985 }
986
987
988 /**
989 * {@inheritDoc}
990 */
991 @Override
992 public FileDownloaderBinder getFileDownloaderBinder() {
993 return mDownloaderBinder;
994 }
995
996
997 /**
998 * {@inheritDoc}
999 */
1000 @Override
1001 public FileUploaderBinder getFileUploaderBinder() {
1002 return mUploaderBinder;
1003 }
1004
1005
1006 /** Defines callbacks for service binding, passed to bindService() */
1007 private class ListServiceConnection implements ServiceConnection {
1008
1009 @Override
1010 public void onServiceConnected(ComponentName component, IBinder service) {
1011 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1012 Log.d(TAG, "Download service connected");
1013 mDownloaderBinder = (FileDownloaderBinder) service;
1014 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1015 Log.d(TAG, "Upload service connected");
1016 mUploaderBinder = (FileUploaderBinder) service;
1017 } else {
1018 return;
1019 }
1020 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1021 if (mFileList != null)
1022 mFileList.listDirectory();
1023 if (mDualPane) {
1024 FileDetailFragment fragment = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1025 if (fragment != null)
1026 fragment.updateFileDetails();
1027 }
1028 }
1029
1030 @Override
1031 public void onServiceDisconnected(ComponentName component) {
1032 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1033 Log.d(TAG, "Download service disconnected");
1034 mDownloaderBinder = null;
1035 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1036 Log.d(TAG, "Upload service disconnected");
1037 mUploaderBinder = null;
1038 }
1039 }
1040 };
1041
1042
1043
1044 /**
1045 * Launch an intent to request the PIN code to the user before letting him use the app
1046 */
1047 private void requestPinCode() {
1048 boolean pinStart = false;
1049 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1050 pinStart = appPrefs.getBoolean("set_pincode", false);
1051 if (pinStart) {
1052 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1053 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1054 startActivity(i);
1055 }
1056 }
1057
1058
1059 @Override
1060 public void onSavedCertificate() {
1061 startSynchronization();
1062 }
1063
1064
1065 @Override
1066 public void onFailedSavingCertificate() {
1067 showDialog(DIALOG_CERT_NOT_SAVED);
1068 }
1069
1070
1071 }