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