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