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