Fixed update of right fragment when actions in the context menu of the left fragment...
[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 long parentDirId = intent.getLongExtra(FileUploader.EXTRA_PARENT_DIR_ID, -1);
878 OCFile parentDir = mStorageManager.getFileById(parentDirId);
879 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
880
881 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&
882 parentDir != null &&
883 ( (mCurrentDir == null && parentDir.getFileName().equals("/")) ||
884 parentDir.equals(mCurrentDir)
885 )
886 ) {
887 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
888 if (fileListFragment != null) {
889 fileListFragment.listDirectory();
890 }
891 }
892 }
893
894 }
895
896
897 /**
898 * Once the file download has finished -> update view
899 */
900 private class DownloadFinishReceiver extends BroadcastReceiver {
901 @Override
902 public void onReceive(Context context, Intent intent) {
903 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
904 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
905
906 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name) &&
907 mCurrentDir != null && mCurrentDir.getFileId() == mStorageManager.getFileByPath(downloadedRemotePath).getParentId()) {
908 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
909 if (fileListFragment != null) {
910 fileListFragment.listDirectory();
911 }
912 }
913 }
914 }
915
916
917
918
919 /**
920 * {@inheritDoc}
921 */
922 @Override
923 public DataStorageManager getStorageManager() {
924 return mStorageManager;
925 }
926
927
928 /**
929 * {@inheritDoc}
930 */
931 @Override
932 public void onDirectoryClick(OCFile directory) {
933 pushDirname(directory);
934 ActionBar actionBar = getSupportActionBar();
935 actionBar.setDisplayHomeAsUpEnabled(true);
936
937 if (mDualPane) {
938 // Resets the FileDetailsFragment on Tablets so that it always displays
939 FileDetailFragment fileDetails = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
940 if (fileDetails != null && !fileDetails.isEmpty()) {
941 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
942 transaction.remove(fileDetails);
943 transaction.add(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG);
944 transaction.commit();
945 }
946 }
947 }
948
949
950 /**
951 * {@inheritDoc}
952 */
953 @Override
954 public void onFileClick(OCFile file) {
955
956 // If we are on a large device -> update fragment
957 if (mDualPane) {
958 // 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'
959 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
960 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
961 transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
962 transaction.commit();
963
964 } else { // small or medium screen device -> new Activity
965 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
966 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
967 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
968 startActivity(showDetailsIntent);
969 }
970 }
971
972
973 /**
974 * {@inheritDoc}
975 */
976 @Override
977 public OCFile getInitialDirectory() {
978 return mCurrentDir;
979 }
980
981
982 /**
983 * {@inheritDoc}
984 */
985 @Override
986 public void onFileStateChanged() {
987 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
988 if (fileListFragment != null) {
989 fileListFragment.listDirectory();
990 }
991 }
992
993
994 /**
995 * {@inheritDoc}
996 */
997 @Override
998 public FileDownloaderBinder getFileDownloaderBinder() {
999 return mDownloaderBinder;
1000 }
1001
1002
1003 /**
1004 * {@inheritDoc}
1005 */
1006 @Override
1007 public FileUploaderBinder getFileUploaderBinder() {
1008 return mUploaderBinder;
1009 }
1010
1011
1012 /** Defines callbacks for service binding, passed to bindService() */
1013 private class ListServiceConnection implements ServiceConnection {
1014
1015 @Override
1016 public void onServiceConnected(ComponentName component, IBinder service) {
1017 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1018 Log.d(TAG, "Download service connected");
1019 mDownloaderBinder = (FileDownloaderBinder) service;
1020 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1021 Log.d(TAG, "Upload service connected");
1022 mUploaderBinder = (FileUploaderBinder) service;
1023 } else {
1024 return;
1025 }
1026 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1027 if (mFileList != null)
1028 mFileList.listDirectory();
1029 if (mDualPane) {
1030 FileDetailFragment fragment = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1031 if (fragment != null)
1032 fragment.updateFileDetails(false);
1033 }
1034 }
1035
1036 @Override
1037 public void onServiceDisconnected(ComponentName component) {
1038 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1039 Log.d(TAG, "Download service disconnected");
1040 mDownloaderBinder = null;
1041 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1042 Log.d(TAG, "Upload service disconnected");
1043 mUploaderBinder = null;
1044 }
1045 }
1046 };
1047
1048
1049
1050 /**
1051 * Launch an intent to request the PIN code to the user before letting him use the app
1052 */
1053 private void requestPinCode() {
1054 boolean pinStart = false;
1055 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1056 pinStart = appPrefs.getBoolean("set_pincode", false);
1057 if (pinStart) {
1058 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1059 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1060 startActivity(i);
1061 }
1062 }
1063
1064
1065 @Override
1066 public void onSavedCertificate() {
1067 startSynchronization();
1068 }
1069
1070
1071 @Override
1072 public void onFailedSavingCertificate() {
1073 showDialog(DIALOG_CERT_NOT_SAVED);
1074 }
1075
1076
1077 /**
1078 * Updates the view associated to the activity after the finish of some operation over files
1079 * in the current account.
1080 *
1081 * @param operation Removal operation performed.
1082 * @param result Result of the removal.
1083 */
1084 @Override
1085 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1086 if (operation instanceof RemoveFileOperation) {
1087 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1088
1089 } else if (operation instanceof RenameFileOperation) {
1090 onRenameFileOperationFinish((RenameFileOperation)operation, result);
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 /**
1168 * {@inheritDoc}
1169 */
1170 @Override
1171 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1172 /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1173 if (fileListFragment != null) {
1174 fileListFragment.listDirectory();
1175 }*/
1176 if (mDualPane) {
1177 FileDetailFragment details = (FileDetailFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1178 if (details != null && file.equals(details.getDisplayedFile()) ) {
1179 if (downloading || uploading) {
1180 details.updateFileDetails(file, AccountUtils.getCurrentOwnCloudAccount(this));
1181 } else {
1182 details.updateFileDetails(downloading || uploading);
1183 }
1184 }
1185 }
1186 }
1187
1188
1189
1190
1191
1192 }