renamed sortDirectory to sortFolder
[pub/Android/ownCloud.git] / src / com / owncloud / android / ui / activity / FileDisplayActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 * Copyright (C) 2012-2014 ownCloud Inc.
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
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 import java.io.IOException;
23
24 import android.accounts.Account;
25 import android.accounts.AccountManager;
26 import android.accounts.AuthenticatorException;
27 import android.accounts.OperationCanceledException;
28 import android.app.AlertDialog;
29 import android.app.Dialog;
30 import android.app.ProgressDialog;
31 import android.content.BroadcastReceiver;
32 import android.content.ComponentName;
33 import android.content.ContentResolver;
34 import android.content.Context;
35 import android.content.DialogInterface;
36 import android.content.Intent;
37 import android.content.IntentFilter;
38 import android.content.ServiceConnection;
39 import android.content.SharedPreferences;
40 import android.content.SyncRequest;
41 import android.content.res.Resources.NotFoundException;
42 import android.database.Cursor;
43 import android.net.Uri;
44 import android.os.Bundle;
45 import android.os.IBinder;
46 import android.preference.PreferenceManager;
47 import android.provider.MediaStore;
48 import android.support.v4.app.Fragment;
49 import android.support.v4.app.FragmentManager;
50 import android.support.v4.app.FragmentTransaction;
51 import android.view.View;
52 import android.view.ViewGroup;
53 import android.widget.ArrayAdapter;
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.view.Menu;
60 import com.actionbarsherlock.view.MenuInflater;
61 import com.actionbarsherlock.view.MenuItem;
62 import com.actionbarsherlock.view.Window;
63 import com.owncloud.android.BuildConfig;
64 import com.owncloud.android.MainApp;
65 import com.owncloud.android.R;
66 import com.owncloud.android.datamodel.OCFile;
67 import com.owncloud.android.files.services.FileDownloader;
68 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
69 import com.owncloud.android.files.services.FileUploader;
70 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
71 import com.owncloud.android.lib.common.OwnCloudAccount;
72 import com.owncloud.android.lib.common.OwnCloudClient;
73 import com.owncloud.android.lib.common.OwnCloudClientManagerFactory;
74 import com.owncloud.android.lib.common.OwnCloudCredentials;
75 import com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException;
76 import com.owncloud.android.lib.common.network.CertificateCombinedException;
77 import com.owncloud.android.lib.common.operations.RemoteOperation;
78 import com.owncloud.android.lib.common.operations.RemoteOperationResult;
79 import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
80 import com.owncloud.android.lib.common.utils.Log_OC;
81 import com.owncloud.android.operations.CreateFolderOperation;
82 import com.owncloud.android.operations.CreateShareOperation;
83 import com.owncloud.android.operations.MoveFileOperation;
84 import com.owncloud.android.operations.RemoveFileOperation;
85 import com.owncloud.android.operations.RenameFileOperation;
86 import com.owncloud.android.operations.SynchronizeFileOperation;
87 import com.owncloud.android.operations.SynchronizeFolderOperation;
88 import com.owncloud.android.operations.UnshareLinkOperation;
89 import com.owncloud.android.services.observer.FileObserverService;
90 import com.owncloud.android.syncadapter.FileSyncAdapter;
91 import com.owncloud.android.ui.adapter.FileListListAdapter;
92 import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
93 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog;
94 import com.owncloud.android.ui.dialog.SslUntrustedCertDialog.OnSslUntrustedCertListener;
95 import com.owncloud.android.ui.fragment.FileDetailFragment;
96 import com.owncloud.android.ui.fragment.FileFragment;
97 import com.owncloud.android.ui.fragment.OCFileListFragment;
98 import com.owncloud.android.ui.preview.PreviewImageActivity;
99 import com.owncloud.android.ui.preview.PreviewImageFragment;
100 import com.owncloud.android.ui.preview.PreviewMediaFragment;
101 import com.owncloud.android.ui.preview.PreviewVideoActivity;
102 import com.owncloud.android.utils.DisplayUtils;
103 import com.owncloud.android.utils.ErrorMessageAdapter;
104 import com.owncloud.android.utils.FileStorageUtils;
105
106
107 /**
108 * Displays, what files the user has available in his ownCloud.
109 *
110 * @author Bartek Przybylski
111 * @author David A. Velasco
112 */
113
114 public class FileDisplayActivity extends HookActivity implements
115 FileFragment.ContainerActivity, OnNavigationListener,
116 OnSslUntrustedCertListener, OnEnforceableRefreshListener {
117
118 private ArrayAdapter<String> mDirectories;
119
120 private SyncBroadcastReceiver mSyncBroadcastReceiver;
121 private UploadFinishReceiver mUploadFinishReceiver;
122 private DownloadFinishReceiver mDownloadFinishReceiver;
123 private RemoteOperationResult mLastSslUntrustedServerResult = null;
124
125 private boolean mDualPane;
126 private View mLeftFragmentContainer;
127 private View mRightFragmentContainer;
128
129 private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
130 private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
131 private static final String KEY_WAITING_TO_SEND = "WAITING_TO_SEND";
132
133 public static final int DIALOG_SHORT_WAIT = 0;
134 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 1;
135 private static final int DIALOG_CERT_NOT_SAVED = 2;
136
137 public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
138
139 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
140 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
141 public static final int ACTION_MOVE_FILES = 3;
142
143 private static final String TAG = FileDisplayActivity.class.getSimpleName();
144
145 private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
146 private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
147
148 private OCFile mWaitingToPreview;
149
150 private boolean mSyncInProgress = false;
151
152 private String DIALOG_UNTRUSTED_CERT;
153
154 private OCFile mWaitingToSend;
155
156 @Override
157 protected void onCreate(Bundle savedInstanceState) {
158 Log_OC.d(TAG, "onCreate() start");
159 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
160
161 super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
162
163 // PIN CODE request ; best location is to decide, let's try this first
164 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
165 requestPinCode();
166 } else if (getIntent().getAction() == null && savedInstanceState == null) {
167 requestPinCode();
168 }
169
170 /// grant that FileObserverService is watching favourite files
171 if (savedInstanceState == null) {
172 Intent initObserversIntent = FileObserverService.makeInitIntent(this);
173 startService(initObserversIntent);
174 }
175
176 /// Load of saved instance state
177 if(savedInstanceState != null) {
178 mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
179 mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
180 mWaitingToSend = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND);
181
182 } else {
183 mWaitingToPreview = null;
184 mSyncInProgress = false;
185 mWaitingToSend = null;
186 }
187
188 /// USER INTERFACE
189
190 // Inflate and set the layout view
191 setContentView(R.layout.files);
192 mDualPane = getResources().getBoolean(R.bool.large_land_layout);
193 mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
194 mRightFragmentContainer = findViewById(R.id.right_fragment_container);
195 if (savedInstanceState == null) {
196 createMinFragments();
197 }
198
199 // Action bar setup
200 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
201 getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
202 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
203
204 setBackgroundText();
205
206 Log_OC.d(TAG, "onCreate() end");
207 }
208
209 @Override
210 protected void onStart() {
211 super.onStart();
212 getSupportActionBar().setIcon(DisplayUtils.getSeasonalIconId());
213 }
214
215 @Override
216 protected void onDestroy() {
217 super.onDestroy();
218 }
219
220 /**
221 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
222 */
223 @Override
224 protected void onAccountSet(boolean stateWasRecovered) {
225 super.onAccountSet(stateWasRecovered);
226 if (getAccount() != null) {
227 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
228 OCFile file = getFile();
229 // get parent from path
230 String parentPath = "";
231 if (file != null) {
232 if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
233 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
234 // get parent from path
235 parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
236 if (getStorageManager().getFileByPath(parentPath) == null)
237 file = null; // not able to know the directory where the file is uploading
238 } else {
239 file = getStorageManager().getFileByPath(file.getRemotePath()); // currentDir = null if not in the current Account
240 }
241 }
242 if (file == null) {
243 // fall back to root folder
244 file = getStorageManager().getFileByPath(OCFile.ROOT_PATH); // never returns null
245 }
246 setFile(file);
247 setNavigationListWithFolder(file);
248
249 if (!stateWasRecovered) {
250 Log_OC.e(TAG, "Initializing Fragments in onAccountChanged..");
251 initFragmentsWithFile();
252 if (file.isFolder()) {
253 startSyncFolderOperation(file, false);
254 }
255
256 } else {
257 updateFragmentsVisibility(!file.isFolder());
258 updateNavigationElementsInActionBar(file.isFolder() ? null : file);
259 }
260 }
261 }
262
263
264 private void setNavigationListWithFolder(OCFile file) {
265 mDirectories.clear();
266 OCFile fileIt = file;
267 String parentPath;
268 while(fileIt != null && fileIt.getFileName() != OCFile.ROOT_PATH) {
269 if (fileIt.isFolder()) {
270 mDirectories.add(fileIt.getFileName());
271 }
272 // get parent from path
273 parentPath = fileIt.getRemotePath().substring(0, fileIt.getRemotePath().lastIndexOf(fileIt.getFileName()));
274 fileIt = getStorageManager().getFileByPath(parentPath);
275 }
276 mDirectories.add(OCFile.PATH_SEPARATOR);
277 }
278
279
280 private void createMinFragments() {
281 OCFileListFragment listOfFiles = new OCFileListFragment();
282 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
283 transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
284 transaction.commit();
285 }
286
287 private void initFragmentsWithFile() {
288 if (getAccount() != null && getFile() != null) {
289 /// First fragment
290 OCFileListFragment listOfFiles = getListOfFilesFragment();
291 if (listOfFiles != null) {
292 listOfFiles.listDirectory(getCurrentDir());
293 } else {
294 Log_OC.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
295 }
296
297 /// Second fragment
298 OCFile file = getFile();
299 Fragment secondFragment = chooseInitialSecondFragment(file);
300 if (secondFragment != null) {
301 setSecondFragment(secondFragment);
302 updateFragmentsVisibility(true);
303 updateNavigationElementsInActionBar(file);
304
305 } else {
306 cleanSecondFragment();
307 }
308
309 } else {
310 Log_OC.wtf(TAG, "initFragments() called with invalid NULLs!");
311 if (getAccount() == null) {
312 Log_OC.wtf(TAG, "\t account is NULL");
313 }
314 if (getFile() == null) {
315 Log_OC.wtf(TAG, "\t file is NULL");
316 }
317 }
318 }
319
320 private Fragment chooseInitialSecondFragment(OCFile file) {
321 Fragment secondFragment = null;
322 if (file != null && !file.isFolder()) {
323 if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
324 && file.getLastSyncDateForProperties() > 0 // temporal fix
325 ) {
326 int startPlaybackPosition = getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
327 boolean autoplay = getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
328 secondFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
329
330 } else {
331 secondFragment = new FileDetailFragment(file, getAccount());
332 }
333 }
334 return secondFragment;
335 }
336
337
338 /**
339 * Replaces the second fragment managed by the activity with the received as
340 * a parameter.
341 *
342 * Assumes never will be more than two fragments managed at the same time.
343 *
344 * @param fragment New second Fragment to set.
345 */
346 private void setSecondFragment(Fragment fragment) {
347 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
348 transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
349 transaction.commit();
350 }
351
352
353 private void updateFragmentsVisibility(boolean existsSecondFragment) {
354 if (mDualPane) {
355 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
356 mLeftFragmentContainer.setVisibility(View.VISIBLE);
357 }
358 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
359 mRightFragmentContainer.setVisibility(View.VISIBLE);
360 }
361
362 } else if (existsSecondFragment) {
363 if (mLeftFragmentContainer.getVisibility() != View.GONE) {
364 mLeftFragmentContainer.setVisibility(View.GONE);
365 }
366 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
367 mRightFragmentContainer.setVisibility(View.VISIBLE);
368 }
369
370 } else {
371 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
372 mLeftFragmentContainer.setVisibility(View.VISIBLE);
373 }
374 if (mRightFragmentContainer.getVisibility() != View.GONE) {
375 mRightFragmentContainer.setVisibility(View.GONE);
376 }
377 }
378 }
379
380
381 private OCFileListFragment getListOfFilesFragment() {
382 Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_LIST_OF_FILES);
383 if (listOfFiles != null) {
384 return (OCFileListFragment)listOfFiles;
385 }
386 Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
387 return null;
388 }
389
390 public FileFragment getSecondFragment() {
391 Fragment second = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT);
392 if (second != null) {
393 return (FileFragment)second;
394 }
395 return null;
396 }
397
398 protected void cleanSecondFragment() {
399 Fragment second = getSecondFragment();
400 if (second != null) {
401 FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
402 tr.remove(second);
403 tr.commit();
404 }
405 updateFragmentsVisibility(false);
406 updateNavigationElementsInActionBar(null);
407 }
408
409 protected void refreshListOfFilesFragment() {
410 OCFileListFragment fileListFragment = getListOfFilesFragment();
411 if (fileListFragment != null) {
412 fileListFragment.listDirectory();
413 }
414 }
415
416 protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath, boolean success) {
417 FileFragment secondFragment = getSecondFragment();
418 boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
419 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
420 FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
421 OCFile fileInFragment = detailsFragment.getFile();
422 if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
423 // the user browsed to other file ; forget the automatic preview
424 mWaitingToPreview = null;
425
426 } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
427 // grant that the right panel updates the progress bar
428 detailsFragment.listenForTransferProgress();
429 detailsFragment.updateFileDetails(true, false);
430
431 } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
432 // update the right panel
433 boolean detailsFragmentChanged = false;
434 if (waitedPreview) {
435 if (success) {
436 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
437 if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
438 startMediaPreview(mWaitingToPreview, 0, true);
439 detailsFragmentChanged = true;
440 } else {
441 getFileOperationsHelper().openFile(mWaitingToPreview);
442 }
443 }
444 mWaitingToPreview = null;
445 }
446 if (!detailsFragmentChanged) {
447 detailsFragment.updateFileDetails(false, (success));
448 }
449 }
450 }
451 }
452
453 @Override
454 public boolean onPrepareOptionsMenu(Menu menu) {
455 if (BuildConfig.DEBUG) {
456 menu.findItem(R.id.action_logger).setVisible(true);
457 } else {
458 menu.findItem(R.id.action_logger).setVisible(false);
459 }
460 return super.onPrepareOptionsMenu(menu);
461 }
462
463 @Override
464 public boolean onCreateOptionsMenu(Menu menu) {
465 MenuInflater inflater = getSherlock().getMenuInflater();
466 inflater.inflate(R.menu.main_menu, menu);
467 return true;
468 }
469
470 @Override
471 public boolean onOptionsItemSelected(MenuItem item) {
472 boolean retval = true;
473 switch (item.getItemId()) {
474 case R.id.action_create_dir: {
475 CreateFolderDialogFragment dialog =
476 CreateFolderDialogFragment.newInstance(getCurrentDir());
477 dialog.show(getSupportFragmentManager(), "createdirdialog");
478 break;
479 }
480 case R.id.action_sync_account: {
481 startSynchronization();
482 break;
483 }
484 case R.id.action_upload: {
485 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
486 break;
487 }
488 case R.id.action_settings: {
489 Intent settingsIntent = new Intent(this, Preferences.class);
490 startActivity(settingsIntent);
491 break;
492 }
493 case R.id.action_logger: {
494 Intent loggerIntent = new Intent(getApplicationContext(),LogHistoryActivity.class);
495 startActivity(loggerIntent);
496 break;
497 }
498 case android.R.id.home: {
499 FileFragment second = getSecondFragment();
500 OCFile currentDir = getCurrentDir();
501 if((currentDir != null && currentDir.getParentId() != 0) ||
502 (second != null && second.getFile() != null)) {
503 onBackPressed();
504
505 }
506 break;
507 }
508 case R.id.action_sort: {
509 SharedPreferences appPreferences = PreferenceManager
510 .getDefaultSharedPreferences(this);
511
512 // Read sorting order, default to sort by name ascending
513 Integer sortOrder = appPreferences
514 .getInt("sortOrder", FileStorageUtils.SORT_NAME);
515
516 AlertDialog.Builder builder = new AlertDialog.Builder(this);
517 builder.setTitle(R.string.actionbar_sort_title)
518 .setSingleChoiceItems(R.array.actionbar_sortby, sortOrder , new DialogInterface.OnClickListener() {
519 public void onClick(DialogInterface dialog, int which) {
520
521 switch (which){
522 case 0:
523 sortByName(true);
524 break;
525 case 1:
526 sortByDate(false);
527 break;
528
529 // TODO re-enable when server-side folder size calculation is available
530 // case 2:
531 // sortBySize(false);
532 // break;
533 }
534
535 dialog.dismiss();
536
537 }
538 });
539 builder.create().show();
540 break;
541 }
542 default:
543 retval = super.onOptionsItemSelected(item);
544 }
545 return retval;
546 }
547
548 private void startSynchronization() {
549 Log_OC.e(TAG, "Got to start sync");
550 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
551 Log_OC.e(TAG, "Canceling all syncs for " + MainApp.getAuthority());
552 ContentResolver.cancelSync(null, MainApp.getAuthority()); // cancel the current synchronizations of any ownCloud account
553 Bundle bundle = new Bundle();
554 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
555 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
556 Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority());
557 ContentResolver.requestSync(
558 getAccount(),
559 MainApp.getAuthority(), bundle);
560 } else {
561 Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority() + " with new API");
562 SyncRequest.Builder builder = new SyncRequest.Builder();
563 builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
564 builder.setExpedited(true);
565 builder.setManual(true);
566 builder.syncOnce();
567 SyncRequest request = builder.build();
568 ContentResolver.requestSync(request);
569 }
570 }
571
572
573 @Override
574 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
575 if (itemPosition != 0) {
576 String targetPath = "";
577 for (int i=itemPosition; i < mDirectories.getCount() - 1; i++) {
578 targetPath = mDirectories.getItem(i) + OCFile.PATH_SEPARATOR + targetPath;
579 }
580 targetPath = OCFile.PATH_SEPARATOR + targetPath;
581 OCFile targetFolder = getStorageManager().getFileByPath(targetPath);
582 if (targetFolder != null) {
583 browseTo(targetFolder);
584 }
585
586 // the next operation triggers a new call to this method, but it's necessary to
587 // ensure that the name exposed in the action bar is the current directory when the
588 // user selected it in the navigation list
589 if (getSupportActionBar().getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST && itemPosition != 0)
590 getSupportActionBar().setSelectedNavigationItem(0);
591 }
592 return true;
593 }
594
595 /**
596 * Called, when the user selected something for uploading
597 */
598 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
599 super.onActivityResult(requestCode, resultCode, data);
600
601 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
602 requestSimpleUpload(data, resultCode);
603
604 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
605 requestMultipleUpload(data, resultCode);
606
607 } else if (requestCode == ACTION_MOVE_FILES && (resultCode == RESULT_OK ||
608 resultCode == MoveActivity.RESULT_OK_AND_MOVE)){
609
610 final Intent fData = data;
611 final int fResultCode = resultCode;
612 getHandler().postDelayed(
613 new Runnable() {
614 @Override
615 public void run() {
616 requestMoveOperation(fData, fResultCode);
617 }
618 },
619 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
620 );
621 }
622 }
623
624 private void requestMultipleUpload(Intent data, int resultCode) {
625 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
626 if (filePaths != null) {
627 String[] remotePaths = new String[filePaths.length];
628 String remotePathBase = "";
629 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
630 remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
631 }
632 if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
633 remotePathBase += OCFile.PATH_SEPARATOR;
634 for (int j = 0; j< remotePaths.length; j++) {
635 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
636 }
637
638 Intent i = new Intent(this, FileUploader.class);
639 i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
640 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
641 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
642 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
643 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
644 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
645 startService(i);
646
647 } else {
648 Log_OC.d(TAG, "User clicked on 'Update' with no selection");
649 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
650 t.show();
651 return;
652 }
653 }
654
655
656 private void requestSimpleUpload(Intent data, int resultCode) {
657 String filepath = null;
658 try {
659 Uri selectedImageUri = data.getData();
660
661 String filemanagerstring = selectedImageUri.getPath();
662 String selectedImagePath = getPath(selectedImageUri);
663
664 if (selectedImagePath != null)
665 filepath = selectedImagePath;
666 else
667 filepath = filemanagerstring;
668
669 } catch (Exception e) {
670 Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
671 e.printStackTrace();
672
673 } finally {
674 if (filepath == null) {
675 Log_OC.e(TAG, "Couldnt resolve path to file");
676 Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
677 t.show();
678 return;
679 }
680 }
681
682 Intent i = new Intent(this, FileUploader.class);
683 i.putExtra(FileUploader.KEY_ACCOUNT,
684 getAccount());
685 String remotepath = new String();
686 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
687 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
688 }
689 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
690 remotepath += OCFile.PATH_SEPARATOR;
691 remotepath += new File(filepath).getName();
692
693 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
694 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
695 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
696 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
697 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
698 startService(i);
699 }
700
701 /**
702 * Request the operation for moving the file/folder from one path to another
703 *
704 * @param data Intent received
705 * @param resultCode Result code received
706 */
707 private void requestMoveOperation(Intent data, int resultCode) {
708 OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(MoveActivity.EXTRA_CURRENT_FOLDER);
709 OCFile targetFile = (OCFile) data.getParcelableExtra(MoveActivity.EXTRA_TARGET_FILE);
710 getFileOperationsHelper().moveFile(folderToMoveAt, targetFile);
711 }
712
713 @Override
714 public void onBackPressed() {
715 OCFileListFragment listOfFiles = getListOfFilesFragment();
716 if (mDualPane || getSecondFragment() == null) {
717 if (listOfFiles != null) { // should never be null, indeed
718 if (mDirectories.getCount() <= 1) {
719 finish();
720 return;
721 }
722 int levelsUp = listOfFiles.onBrowseUp();
723 for (int i=0; i < levelsUp && mDirectories.getCount() > 1 ; i++) {
724 popDirname();
725 }
726 }
727 }
728 if (listOfFiles != null) { // should never be null, indeed
729 setFile(listOfFiles.getCurrentFile());
730 }
731 cleanSecondFragment();
732
733 }
734
735 @Override
736 protected void onSaveInstanceState(Bundle outState) {
737 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
738 Log_OC.e(TAG, "onSaveInstanceState() start");
739 super.onSaveInstanceState(outState);
740 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
741 outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
742 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
743 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
744
745 Log_OC.d(TAG, "onSaveInstanceState() end");
746 }
747
748
749
750 @Override
751 protected void onResume() {
752 super.onResume();
753 Log_OC.e(TAG, "onResume() start");
754
755 // refresh list of files
756 refreshListOfFilesFragment();
757
758 // Listen for sync messages
759 IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
760 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
761 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
762 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
763 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
764 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
765 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
766 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
767
768 // Listen for upload messages
769 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
770 mUploadFinishReceiver = new UploadFinishReceiver();
771 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
772
773 // Listen for download messages
774 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
775 downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
776 mDownloadFinishReceiver = new DownloadFinishReceiver();
777 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
778
779 Log_OC.d(TAG, "onResume() end");
780 }
781
782
783 @Override
784 protected void onPause() {
785 Log_OC.e(TAG, "onPause() start");
786 if (mSyncBroadcastReceiver != null) {
787 unregisterReceiver(mSyncBroadcastReceiver);
788 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
789 mSyncBroadcastReceiver = null;
790 }
791 if (mUploadFinishReceiver != null) {
792 unregisterReceiver(mUploadFinishReceiver);
793 mUploadFinishReceiver = null;
794 }
795 if (mDownloadFinishReceiver != null) {
796 unregisterReceiver(mDownloadFinishReceiver);
797 mDownloadFinishReceiver = null;
798 }
799
800
801 Log_OC.d(TAG, "onPause() end");
802 super.onPause();
803 }
804
805
806 @Override
807 protected Dialog onCreateDialog(int id) {
808 Dialog dialog = null;
809 AlertDialog.Builder builder;
810 switch (id) {
811 case DIALOG_SHORT_WAIT: {
812 ProgressDialog working_dialog = new ProgressDialog(this);
813 working_dialog.setMessage(getResources().getString(
814 R.string.wait_a_moment));
815 working_dialog.setIndeterminate(true);
816 working_dialog.setCancelable(false);
817 dialog = working_dialog;
818 break;
819 }
820 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
821
822
823 String[] allTheItems = { getString(R.string.actionbar_upload_files),
824 getString(R.string.actionbar_upload_from_apps) };
825
826 builder = new AlertDialog.Builder(this);
827 builder.setTitle(R.string.actionbar_upload);
828 builder.setItems(allTheItems, new DialogInterface.OnClickListener() {
829 public void onClick(DialogInterface dialog, int item) {
830 if (item == 0) {
831 // if (!mDualPane) {
832 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
833 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
834 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
835 // } else {
836 // TODO create and handle new fragment
837 // LocalFileListFragment
838 // }
839 } else if (item == 1) {
840 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
841 action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
842 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
843 ACTION_SELECT_CONTENT_FROM_APPS);
844 }
845 }
846 });
847 dialog = builder.create();
848 break;
849 }
850 case DIALOG_CERT_NOT_SAVED: {
851 builder = new AlertDialog.Builder(this);
852 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
853 builder.setCancelable(false);
854 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
855 @Override
856 public void onClick(DialogInterface dialog, int which) {
857 dialog.dismiss();
858 };
859 });
860 dialog = builder.create();
861 break;
862 }
863 default:
864 dialog = null;
865 }
866
867 return dialog;
868 }
869
870
871 /**
872 * Translates a content URI of an image to a physical path
873 * on the disk
874 * @param uri The URI to resolve
875 * @return The path to the image or null if it could not be found
876 */
877 public String getPath(Uri uri) {
878 String[] projection = { MediaStore.Images.Media.DATA };
879 Cursor cursor = managedQuery(uri, projection, null, null, null);
880 if (cursor != null) {
881 int column_index = cursor
882 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
883 cursor.moveToFirst();
884 return cursor.getString(column_index);
885 }
886 return null;
887 }
888
889 /**
890 * Pushes a directory to the drop down list
891 * @param directory to push
892 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
893 */
894 public void pushDirname(OCFile directory) {
895 if(!directory.isFolder()){
896 throw new IllegalArgumentException("Only directories may be pushed!");
897 }
898 mDirectories.insert(directory.getFileName(), 0);
899 setFile(directory);
900 }
901
902 /**
903 * Pops a directory name from the drop down list
904 * @return True, unless the stack is empty
905 */
906 public boolean popDirname() {
907 mDirectories.remove(mDirectories.getItem(0));
908 return !mDirectories.isEmpty();
909 }
910
911 // Custom array adapter to override text colors
912 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
913
914 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
915 super(ctx, view);
916 }
917
918 public View getView(int position, View convertView, ViewGroup parent) {
919 View v = super.getView(position, convertView, parent);
920
921 ((TextView) v).setTextColor(getResources().getColorStateList(
922 android.R.color.white));
923
924 fixRoot((TextView) v );
925 return v;
926 }
927
928 public View getDropDownView(int position, View convertView,
929 ViewGroup parent) {
930 View v = super.getDropDownView(position, convertView, parent);
931
932 ((TextView) v).setTextColor(getResources().getColorStateList(
933 android.R.color.white));
934
935 fixRoot((TextView) v );
936 return v;
937 }
938
939 private void fixRoot(TextView v) {
940 if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
941 v.setText(R.string.default_display_name_for_root_folder);
942 }
943 }
944
945 }
946
947 private class SyncBroadcastReceiver extends BroadcastReceiver {
948
949 /**
950 * {@link BroadcastReceiver} to enable syncing feedback in UI
951 */
952 @Override
953 public void onReceive(Context context, Intent intent) {
954 try {
955 String event = intent.getAction();
956 Log_OC.d(TAG, "Received broadcast " + event);
957 String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
958 String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
959 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
960 boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
961
962 if (sameAccount) {
963
964 if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
965 mSyncInProgress = true;
966
967 } else {
968 OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
969 OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
970
971 if (currentDir == null) {
972 // current folder was removed from the server
973 Toast.makeText( FileDisplayActivity.this,
974 String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
975 Toast.LENGTH_LONG)
976 .show();
977 browseToRoot();
978
979 } else {
980 if (currentFile == null && !getFile().isFolder()) {
981 // currently selected file was removed in the server, and now we know it
982 cleanSecondFragment();
983 currentFile = currentDir;
984 }
985
986 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
987 OCFileListFragment fileListFragment = getListOfFilesFragment();
988 if (fileListFragment != null) {
989 fileListFragment.listDirectory(currentDir);
990 }
991 }
992 setFile(currentFile);
993 }
994
995 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
996
997 if (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
998 equals(event) &&
999 /// TODO refactor and make common
1000 synchResult != null && !synchResult.isSuccess() &&
1001 (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
1002 synchResult.isIdPRedirection() ||
1003 (synchResult.isException() && synchResult.getException()
1004 instanceof AuthenticatorException))) {
1005
1006 OwnCloudClient client = null;
1007 try {
1008 OwnCloudAccount ocAccount =
1009 new OwnCloudAccount(getAccount(), context);
1010 client = (OwnCloudClientManagerFactory.getDefaultSingleton().
1011 removeClientFor(ocAccount));
1012 // TODO get rid of these exceptions
1013 } catch (AccountNotFoundException e) {
1014 e.printStackTrace();
1015 } catch (AuthenticatorException e) {
1016 e.printStackTrace();
1017 } catch (OperationCanceledException e) {
1018 e.printStackTrace();
1019 } catch (IOException e) {
1020 e.printStackTrace();
1021 }
1022
1023 if (client != null) {
1024 OwnCloudCredentials cred = client.getCredentials();
1025 if (cred != null) {
1026 AccountManager am = AccountManager.get(context);
1027 if (cred.authTokenExpires()) {
1028 am.invalidateAuthToken(
1029 getAccount().type,
1030 cred.getAuthToken()
1031 );
1032 } else {
1033 am.clearPassword(getAccount());
1034 }
1035 }
1036 }
1037
1038 requestCredentialsUpdate();
1039
1040 }
1041 }
1042 removeStickyBroadcast(intent);
1043 Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
1044 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
1045
1046 setBackgroundText();
1047
1048 }
1049
1050 if (synchResult != null) {
1051 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
1052 mLastSslUntrustedServerResult = synchResult;
1053 }
1054 }
1055 } catch (RuntimeException e) {
1056 // avoid app crashes after changing the serial id of RemoteOperationResult
1057 // in owncloud library with broadcast notifications pending to process
1058 removeStickyBroadcast(intent);
1059 }
1060 }
1061 }
1062
1063 /**
1064 * Show a text message on screen view for notifying user if content is
1065 * loading or folder is empty
1066 */
1067 private void setBackgroundText() {
1068 OCFileListFragment ocFileListFragment = getListOfFilesFragment();
1069 if (ocFileListFragment != null) {
1070 int message = R.string.file_list_loading;
1071 if (!mSyncInProgress) {
1072 // In case file list is empty
1073 message = R.string.file_list_empty;
1074 }
1075 ocFileListFragment.setMessageForEmptyList(getString(message));
1076 } else {
1077 Log_OC.e(TAG, "OCFileListFragment is null");
1078 }
1079 }
1080
1081 /**
1082 * Once the file upload has finished -> update view
1083 */
1084 private class UploadFinishReceiver extends BroadcastReceiver {
1085 /**
1086 * Once the file upload has finished -> update view
1087 * @author David A. Velasco
1088 * {@link BroadcastReceiver} to enable upload feedback in UI
1089 */
1090 @Override
1091 public void onReceive(Context context, Intent intent) {
1092 try {
1093 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1094 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
1095 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
1096 OCFile currentDir = getCurrentDir();
1097 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
1098 (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
1099
1100 if (sameAccount && isDescendant) {
1101 refreshListOfFilesFragment();
1102 }
1103
1104 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
1105 boolean renamedInUpload = getFile().getRemotePath().
1106 equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
1107 boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
1108 renamedInUpload;
1109 FileFragment details = getSecondFragment();
1110 boolean detailFragmentIsShown = (details != null &&
1111 details instanceof FileDetailFragment);
1112
1113 if (sameAccount && sameFile && detailFragmentIsShown) {
1114 if (uploadWasFine) {
1115 setFile(getStorageManager().getFileByPath(uploadedRemotePath));
1116 }
1117 if (renamedInUpload) {
1118 String newName = (new File(uploadedRemotePath)).getName();
1119 Toast msg = Toast.makeText(
1120 context,
1121 String.format(
1122 getString(R.string.filedetails_renamed_in_upload_msg),
1123 newName),
1124 Toast.LENGTH_LONG);
1125 msg.show();
1126 }
1127 if (uploadWasFine || getFile().fileExists()) {
1128 ((FileDetailFragment)details).updateFileDetails(false, true);
1129 } else {
1130 cleanSecondFragment();
1131 }
1132
1133 // Force the preview if the file is an image
1134 if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
1135 startImagePreview(getFile());
1136 } // TODO what about other kind of previews?
1137 }
1138
1139 } finally {
1140 if (intent != null) {
1141 removeStickyBroadcast(intent);
1142 }
1143 }
1144
1145 }
1146
1147 }
1148
1149
1150 /**
1151 * Class waiting for broadcast events from the {@link FielDownloader} service.
1152 *
1153 * Updates the UI when a download is started or finished, provided that it is relevant for the
1154 * current folder.
1155 */
1156 private class DownloadFinishReceiver extends BroadcastReceiver {
1157 @Override
1158 public void onReceive(Context context, Intent intent) {
1159 try {
1160 boolean sameAccount = isSameAccount(context, intent);
1161 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1162 boolean isDescendant = isDescendant(downloadedRemotePath);
1163
1164 if (sameAccount && isDescendant) {
1165 refreshListOfFilesFragment();
1166 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1167 }
1168
1169 if (mWaitingToSend != null) {
1170 mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath()); // Update the file to send
1171 if (mWaitingToSend.isDown()) {
1172 sendDownloadedFile();
1173 }
1174 }
1175
1176 } finally {
1177 if (intent != null) {
1178 removeStickyBroadcast(intent);
1179 }
1180 }
1181 }
1182
1183 private boolean isDescendant(String downloadedRemotePath) {
1184 OCFile currentDir = getCurrentDir();
1185 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
1186 }
1187
1188 private boolean isSameAccount(Context context, Intent intent) {
1189 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1190 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1191 }
1192 }
1193
1194
1195 public void browseToRoot() {
1196 OCFileListFragment listOfFiles = getListOfFilesFragment();
1197 if (listOfFiles != null) { // should never be null, indeed
1198 while (mDirectories.getCount() > 1) {
1199 popDirname();
1200 }
1201 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1202 listOfFiles.listDirectory(root);
1203 setFile(listOfFiles.getCurrentFile());
1204 startSyncFolderOperation(root, false);
1205 }
1206 cleanSecondFragment();
1207 }
1208
1209
1210 public void browseTo(OCFile folder) {
1211 if (folder == null || !folder.isFolder()) {
1212 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1213 }
1214 OCFileListFragment listOfFiles = getListOfFilesFragment();
1215 if (listOfFiles != null) {
1216 setNavigationListWithFolder(folder);
1217 listOfFiles.listDirectory(folder);
1218 setFile(listOfFiles.getCurrentFile());
1219 startSyncFolderOperation(folder, false);
1220 } else {
1221 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1222 }
1223 cleanSecondFragment();
1224 }
1225
1226
1227 /**
1228 * {@inheritDoc}
1229 *
1230 * Updates action bar and second fragment, if in dual pane mode.
1231 */
1232 @Override
1233 public void onBrowsedDownTo(OCFile directory) {
1234 pushDirname(directory);
1235 cleanSecondFragment();
1236
1237 // Sync Folder
1238 startSyncFolderOperation(directory, false);
1239
1240 }
1241
1242 /**
1243 * Shows the information of the {@link OCFile} received as a
1244 * parameter in the second fragment.
1245 *
1246 * @param file {@link OCFile} whose details will be shown
1247 */
1248 @Override
1249 public void showDetails(OCFile file) {
1250 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1251 setSecondFragment(detailFragment);
1252 updateFragmentsVisibility(true);
1253 updateNavigationElementsInActionBar(file);
1254 setFile(file);
1255 }
1256
1257
1258 /**
1259 * TODO
1260 */
1261 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1262 ActionBar actionBar = getSupportActionBar();
1263 if (chosenFile == null || mDualPane) {
1264 // only list of files - set for browsing through folders
1265 OCFile currentDir = getCurrentDir();
1266 boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
1267 actionBar.setDisplayHomeAsUpEnabled(noRoot);
1268 actionBar.setDisplayShowTitleEnabled(!noRoot);
1269 if (!noRoot) {
1270 actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
1271 }
1272 actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
1273 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1274
1275 } else {
1276 actionBar.setDisplayHomeAsUpEnabled(true);
1277 actionBar.setDisplayShowTitleEnabled(true);
1278 actionBar.setTitle(chosenFile.getFileName());
1279 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1280 }
1281 }
1282
1283
1284 @Override
1285 protected ServiceConnection newTransferenceServiceConnection() {
1286 return new ListServiceConnection();
1287 }
1288
1289 /** Defines callbacks for service binding, passed to bindService() */
1290 private class ListServiceConnection implements ServiceConnection {
1291
1292 @Override
1293 public void onServiceConnected(ComponentName component, IBinder service) {
1294 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1295 Log_OC.d(TAG, "Download service connected");
1296 mDownloaderBinder = (FileDownloaderBinder) service;
1297 if (mWaitingToPreview != null)
1298 if (getStorageManager() != null) {
1299 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file
1300 if (!mWaitingToPreview.isDown()) {
1301 requestForDownload();
1302 }
1303 }
1304
1305 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1306 Log_OC.d(TAG, "Upload service connected");
1307 mUploaderBinder = (FileUploaderBinder) service;
1308 } else {
1309 return;
1310 }
1311 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1312 OCFileListFragment listOfFiles = getListOfFilesFragment();
1313 if (listOfFiles != null) {
1314 listOfFiles.listDirectory();
1315 }
1316 FileFragment secondFragment = getSecondFragment();
1317 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1318 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1319 detailFragment.listenForTransferProgress();
1320 detailFragment.updateFileDetails(false, false);
1321 }
1322 }
1323
1324 @Override
1325 public void onServiceDisconnected(ComponentName component) {
1326 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1327 Log_OC.d(TAG, "Download service disconnected");
1328 mDownloaderBinder = null;
1329 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1330 Log_OC.d(TAG, "Upload service disconnected");
1331 mUploaderBinder = null;
1332 }
1333 }
1334 };
1335
1336
1337
1338 /**
1339 * Launch an intent to request the PIN code to the user before letting him use the app
1340 */
1341 private void requestPinCode() {
1342 boolean pinStart = false;
1343 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1344 pinStart = appPrefs.getBoolean("set_pincode", false);
1345 if (pinStart) {
1346 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1347 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1348 startActivity(i);
1349 }
1350 }
1351
1352
1353 @Override
1354 public void onSavedCertificate() {
1355 startSyncFolderOperation(getCurrentDir(), false);
1356 }
1357
1358
1359 @Override
1360 public void onFailedSavingCertificate() {
1361 showDialog(DIALOG_CERT_NOT_SAVED);
1362 }
1363
1364 @Override
1365 public void onCancelCertificate() {
1366 // nothing to do
1367 }
1368
1369 /**
1370 * Updates the view associated to the activity after the finish of some operation over files
1371 * in the current account.
1372 *
1373 * @param operation Removal operation performed.
1374 * @param result Result of the removal.
1375 */
1376 @Override
1377 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1378 super.onRemoteOperationFinish(operation, result);
1379
1380 if (operation instanceof RemoveFileOperation) {
1381 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1382
1383 } else if (operation instanceof RenameFileOperation) {
1384 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1385
1386 } else if (operation instanceof SynchronizeFileOperation) {
1387 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1388
1389 } else if (operation instanceof CreateFolderOperation) {
1390 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1391
1392 } else if (operation instanceof CreateShareOperation) {
1393 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1394
1395 } else if (operation instanceof UnshareLinkOperation) {
1396 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
1397
1398 } else if (operation instanceof MoveFileOperation) {
1399 onMoveFileOperationFinish((MoveFileOperation)operation, result);
1400 }
1401
1402 }
1403
1404
1405 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
1406 if (result.isSuccess()) {
1407 refreshShowDetails();
1408 refreshListOfFilesFragment();
1409 }
1410 }
1411
1412
1413 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
1414 if (result.isSuccess()) {
1415 refreshShowDetails();
1416 refreshListOfFilesFragment();
1417
1418 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
1419 cleanSecondFragment();
1420 refreshListOfFilesFragment();
1421 }
1422 }
1423
1424 private void refreshShowDetails() {
1425 FileFragment details = getSecondFragment();
1426 if (details != null) {
1427 OCFile file = details.getFile();
1428 if (file != null) {
1429 file = getStorageManager().getFileByPath(file.getRemotePath());
1430 if (details instanceof PreviewMediaFragment) {
1431 // Refresh OCFile of the fragment
1432 ((PreviewMediaFragment) details).updateFile(file);
1433 } else {
1434 showDetails(file);
1435 }
1436 }
1437 invalidateOptionsMenu();
1438 }
1439 }
1440
1441 /**
1442 * Updates the view associated to the activity after the finish of an operation trying to remove a
1443 * file.
1444 *
1445 * @param operation Removal operation performed.
1446 * @param result Result of the removal.
1447 */
1448 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1449 dismissLoadingDialog();
1450
1451 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1452 Toast.LENGTH_LONG);
1453 msg.show();
1454
1455 if (result.isSuccess()) {
1456 OCFile removedFile = operation.getFile();
1457 FileFragment second = getSecondFragment();
1458 if (second != null && removedFile.equals(second.getFile())) {
1459 if (second instanceof PreviewMediaFragment) {
1460 ((PreviewMediaFragment)second).stopPreview(true);
1461 }
1462 setFile(getStorageManager().getFileById(removedFile.getParentId()));
1463 cleanSecondFragment();
1464 }
1465 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1466 refreshListOfFilesFragment();
1467 }
1468 invalidateOptionsMenu();
1469 } else {
1470 if (result.isSslRecoverableException()) {
1471 mLastSslUntrustedServerResult = result;
1472 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1473 }
1474 }
1475 }
1476
1477
1478 /**
1479 * Updates the view associated to the activity after the finish of an operation trying to move a
1480 * file.
1481 *
1482 * @param operation Move operation performed.
1483 * @param result Result of the move operation.
1484 */
1485 private void onMoveFileOperationFinish(MoveFileOperation operation, RemoteOperationResult result) {
1486 if (result.isSuccess()) {
1487 dismissLoadingDialog();
1488 refreshListOfFilesFragment();
1489 } else {
1490 dismissLoadingDialog();
1491 try {
1492 Toast msg = Toast.makeText(FileDisplayActivity.this,
1493 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1494 Toast.LENGTH_LONG);
1495 msg.show();
1496
1497 } catch (NotFoundException e) {
1498 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1499 }
1500 }
1501 }
1502
1503
1504 /**
1505 * Updates the view associated to the activity after the finish of an operation trying to rename a
1506 * file.
1507 *
1508 * @param operation Renaming operation performed.
1509 * @param result Result of the renaming.
1510 */
1511 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1512 dismissLoadingDialog();
1513 OCFile renamedFile = operation.getFile();
1514 if (result.isSuccess()) {
1515 FileFragment details = getSecondFragment();
1516 if (details != null) {
1517 if (details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1518 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1519 showDetails(renamedFile);
1520
1521 } else if (details instanceof PreviewMediaFragment && renamedFile.equals(details.getFile())) {
1522 ((PreviewMediaFragment) details).updateFile(renamedFile);
1523 if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
1524 int position = ((PreviewMediaFragment)details).getPosition();
1525 startMediaPreview(renamedFile, position, true);
1526 } else {
1527 getFileOperationsHelper().openFile(renamedFile);
1528 }
1529 }
1530 }
1531
1532 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1533 refreshListOfFilesFragment();
1534 }
1535
1536 } else {
1537 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1538 Toast.LENGTH_LONG);
1539 msg.show();
1540
1541 if (result.isSslRecoverableException()) {
1542 mLastSslUntrustedServerResult = result;
1543 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1544 }
1545 }
1546 }
1547
1548 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1549 dismissLoadingDialog();
1550 OCFile syncedFile = operation.getLocalFile();
1551 if (!result.isSuccess()) {
1552 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1553 Intent i = new Intent(this, ConflictsResolveActivity.class);
1554 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1555 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1556 startActivity(i);
1557
1558 }
1559
1560 } else {
1561 if (operation.transferWasRequested()) {
1562 onTransferStateChanged(syncedFile, true, true);
1563
1564 } else {
1565 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1566 Toast.LENGTH_LONG);
1567 msg.show();
1568 }
1569 }
1570 }
1571
1572 /**
1573 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1574 *
1575 * @param operation Creation operation performed.
1576 * @param result Result of the creation.
1577 */
1578 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1579 if (result.isSuccess()) {
1580 dismissLoadingDialog();
1581 refreshListOfFilesFragment();
1582 } else {
1583 dismissLoadingDialog();
1584 try {
1585 Toast msg = Toast.makeText(FileDisplayActivity.this,
1586 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1587 Toast.LENGTH_LONG);
1588 msg.show();
1589
1590 } catch (NotFoundException e) {
1591 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1592 }
1593 }
1594 }
1595
1596
1597 /**
1598 * {@inheritDoc}
1599 */
1600 @Override
1601 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1602 refreshListOfFilesFragment();
1603 FileFragment details = getSecondFragment();
1604 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1605 if (downloading || uploading) {
1606 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1607 } else {
1608 if (!file.fileExists()) {
1609 cleanSecondFragment();
1610 } else {
1611 ((FileDetailFragment)details).updateFileDetails(false, true);
1612 }
1613 }
1614 }
1615
1616 }
1617
1618
1619 private void requestForDownload() {
1620 Account account = getAccount();
1621 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1622 Intent i = new Intent(this, FileDownloader.class);
1623 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1624 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1625 startService(i);
1626 }
1627 }
1628
1629
1630 private OCFile getCurrentDir() {
1631 OCFile file = getFile();
1632 if (file != null) {
1633 if (file.isFolder()) {
1634 return file;
1635 } else if (getStorageManager() != null) {
1636 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
1637 return getStorageManager().getFileByPath(parentPath);
1638 }
1639 }
1640 return null;
1641 }
1642
1643 public void startSyncFolderOperation(OCFile folder, boolean ignoreETag) {
1644 long currentSyncTime = System.currentTimeMillis();
1645
1646 mSyncInProgress = true;
1647
1648 // perform folder synchronization
1649 RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
1650 currentSyncTime,
1651 false,
1652 getFileOperationsHelper().isSharedSupported(),
1653 ignoreETag,
1654 getStorageManager(),
1655 getAccount(),
1656 getApplicationContext()
1657 );
1658 synchFolderOp.execute(getAccount(), this, null, null);
1659
1660 setSupportProgressBarIndeterminateVisibility(true);
1661
1662 setBackgroundText();
1663 }
1664
1665 /**
1666 * Show untrusted cert dialog
1667 */
1668 public void showUntrustedCertDialog(RemoteOperationResult result) {
1669 // Show a dialog with the certificate info
1670 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());
1671 FragmentManager fm = getSupportFragmentManager();
1672 FragmentTransaction ft = fm.beginTransaction();
1673 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
1674 }
1675
1676 private void requestForDownload(OCFile file) {
1677 Account account = getAccount();
1678 if (!mDownloaderBinder.isDownloading(account, file)) {
1679 Intent i = new Intent(this, FileDownloader.class);
1680 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1681 i.putExtra(FileDownloader.EXTRA_FILE, file);
1682 startService(i);
1683 }
1684 }
1685
1686 private void sendDownloadedFile(){
1687 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
1688 mWaitingToSend = null;
1689 }
1690
1691
1692 /**
1693 * Requests the download of the received {@link OCFile} , updates the UI
1694 * to monitor the download progress and prepares the activity to send the file
1695 * when the download finishes.
1696 *
1697 * @param file {@link OCFile} to download and preview.
1698 */
1699 public void startDownloadForSending(OCFile file) {
1700 mWaitingToSend = file;
1701 requestForDownload(mWaitingToSend);
1702 boolean hasSecondFragment = (getSecondFragment()!= null);
1703 updateFragmentsVisibility(hasSecondFragment);
1704 }
1705
1706 /**
1707 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1708 *
1709 * @param file Image {@link OCFile} to show.
1710 */
1711 public void startImagePreview(OCFile file) {
1712 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1713 showDetailsIntent.putExtra(EXTRA_FILE, file);
1714 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1715 startActivity(showDetailsIntent);
1716
1717 }
1718
1719 /**
1720 * Stars the preview of an already down media {@link OCFile}.
1721 *
1722 * @param file Media {@link OCFile} to preview.
1723 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1724 * @param autoplay When 'true', the playback will start without user interactions.
1725 */
1726 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1727 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1728 setSecondFragment(mediaFragment);
1729 updateFragmentsVisibility(true);
1730 updateNavigationElementsInActionBar(file);
1731 setFile(file);
1732 }
1733
1734 /**
1735 * Requests the download of the received {@link OCFile} , updates the UI
1736 * to monitor the download progress and prepares the activity to preview
1737 * or open the file when the download finishes.
1738 *
1739 * @param file {@link OCFile} to download and preview.
1740 */
1741 public void startDownloadForPreview(OCFile file) {
1742 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1743 setSecondFragment(detailFragment);
1744 mWaitingToPreview = file;
1745 requestForDownload();
1746 updateFragmentsVisibility(true);
1747 updateNavigationElementsInActionBar(file);
1748 setFile(file);
1749 }
1750
1751
1752 public void cancelTransference(OCFile file) {
1753 getFileOperationsHelper().cancelTransference(file);
1754 if (mWaitingToPreview != null &&
1755 mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
1756 mWaitingToPreview = null;
1757 }
1758 if (mWaitingToSend != null &&
1759 mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
1760 mWaitingToSend = null;
1761 }
1762 onTransferStateChanged(file, false, false);
1763 }
1764
1765 @Override
1766 public void onRefresh(boolean ignoreETag) {
1767 refreshList(ignoreETag);
1768 }
1769
1770 @Override
1771 public void onRefresh() {
1772 refreshList(true);
1773 }
1774
1775 private void refreshList(boolean ignoreETag) {
1776 OCFileListFragment listOfFiles = getListOfFilesFragment();
1777 if (listOfFiles != null) {
1778 OCFile folder = listOfFiles.getCurrentFile();
1779 if (folder != null) {
1780 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1781 listDirectory(mFile);*/
1782 startSyncFolderOperation(folder, ignoreETag);
1783 }
1784 }
1785 }
1786
1787 private void sortByDate(boolean ascending){
1788 getListOfFilesFragment().sortByDate(ascending);
1789 }
1790
1791 private void sortBySize(boolean ascending){
1792 getListOfFilesFragment().sortBySize(ascending);
1793 }
1794
1795 private void sortByName(boolean ascending){
1796 getListOfFilesFragment().sortByName(ascending);
1797 }
1798 }