- disabled sort by size until server supports server-side folder size
[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
515 // TODO re-enable when server-side folder size calculation is available
516 // case 2:
517 // sortBySize(false);
518 // break;
519 }
520
521 dialog.dismiss();
522
523 }
524 });
525 builder.create().show();
526 break;
527 }
528 default:
529 retval = super.onOptionsItemSelected(item);
530 }
531 return retval;
532 }
533
534 private void startSynchronization() {
535 Log_OC.e(TAG, "Got to start sync");
536 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
537 Log_OC.e(TAG, "Canceling all syncs for " + MainApp.getAuthority());
538 ContentResolver.cancelSync(null, MainApp.getAuthority()); // cancel the current synchronizations of any ownCloud account
539 Bundle bundle = new Bundle();
540 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
541 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
542 Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority());
543 ContentResolver.requestSync(
544 getAccount(),
545 MainApp.getAuthority(), bundle);
546 } else {
547 Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority() + " with new API");
548 SyncRequest.Builder builder = new SyncRequest.Builder();
549 builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
550 builder.setExpedited(true);
551 builder.setManual(true);
552 builder.syncOnce();
553 SyncRequest request = builder.build();
554 ContentResolver.requestSync(request);
555 }
556 }
557
558
559 @Override
560 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
561 if (itemPosition != 0) {
562 String targetPath = "";
563 for (int i=itemPosition; i < mDirectories.getCount() - 1; i++) {
564 targetPath = mDirectories.getItem(i) + OCFile.PATH_SEPARATOR + targetPath;
565 }
566 targetPath = OCFile.PATH_SEPARATOR + targetPath;
567 OCFile targetFolder = getStorageManager().getFileByPath(targetPath);
568 if (targetFolder != null) {
569 browseTo(targetFolder);
570 }
571
572 // the next operation triggers a new call to this method, but it's necessary to
573 // ensure that the name exposed in the action bar is the current directory when the
574 // user selected it in the navigation list
575 if (getSupportActionBar().getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST && itemPosition != 0)
576 getSupportActionBar().setSelectedNavigationItem(0);
577 }
578 return true;
579 }
580
581 /**
582 * Called, when the user selected something for uploading
583 */
584 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
585 super.onActivityResult(requestCode, resultCode, data);
586
587 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
588 requestSimpleUpload(data, resultCode);
589
590 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
591 requestMultipleUpload(data, resultCode);
592
593 } else if (requestCode == ACTION_MOVE_FILES && (resultCode == RESULT_OK ||
594 resultCode == MoveActivity.RESULT_OK_AND_MOVE)){
595
596 final Intent fData = data;
597 final int fResultCode = resultCode;
598 getHandler().postDelayed(
599 new Runnable() {
600 @Override
601 public void run() {
602 requestMoveOperation(fData, fResultCode);
603 }
604 },
605 DELAY_TO_REQUEST_OPERATION_ON_ACTIVITY_RESULTS
606 );
607 }
608 }
609
610 private void requestMultipleUpload(Intent data, int resultCode) {
611 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
612 if (filePaths != null) {
613 String[] remotePaths = new String[filePaths.length];
614 String remotePathBase = "";
615 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
616 remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
617 }
618 if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
619 remotePathBase += OCFile.PATH_SEPARATOR;
620 for (int j = 0; j< remotePaths.length; j++) {
621 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
622 }
623
624 Intent i = new Intent(this, FileUploader.class);
625 i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
626 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
627 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
628 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
629 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
630 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
631 startService(i);
632
633 } else {
634 Log_OC.d(TAG, "User clicked on 'Update' with no selection");
635 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
636 t.show();
637 return;
638 }
639 }
640
641
642 private void requestSimpleUpload(Intent data, int resultCode) {
643 String filepath = null;
644 try {
645 Uri selectedImageUri = data.getData();
646
647 String filemanagerstring = selectedImageUri.getPath();
648 String selectedImagePath = getPath(selectedImageUri);
649
650 if (selectedImagePath != null)
651 filepath = selectedImagePath;
652 else
653 filepath = filemanagerstring;
654
655 } catch (Exception e) {
656 Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
657 e.printStackTrace();
658
659 } finally {
660 if (filepath == null) {
661 Log_OC.e(TAG, "Couldnt resolve path to file");
662 Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
663 t.show();
664 return;
665 }
666 }
667
668 Intent i = new Intent(this, FileUploader.class);
669 i.putExtra(FileUploader.KEY_ACCOUNT,
670 getAccount());
671 String remotepath = new String();
672 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
673 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
674 }
675 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
676 remotepath += OCFile.PATH_SEPARATOR;
677 remotepath += new File(filepath).getName();
678
679 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
680 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
681 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
682 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
683 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
684 startService(i);
685 }
686
687 /**
688 * Request the operation for moving the file/folder from one path to another
689 *
690 * @param data Intent received
691 * @param resultCode Result code received
692 */
693 private void requestMoveOperation(Intent data, int resultCode) {
694 OCFile folderToMoveAt = (OCFile) data.getParcelableExtra(MoveActivity.EXTRA_CURRENT_FOLDER);
695 OCFile targetFile = (OCFile) data.getParcelableExtra(MoveActivity.EXTRA_TARGET_FILE);
696 getFileOperationsHelper().moveFile(folderToMoveAt, targetFile);
697 }
698
699 @Override
700 public void onBackPressed() {
701 OCFileListFragment listOfFiles = getListOfFilesFragment();
702 if (mDualPane || getSecondFragment() == null) {
703 if (listOfFiles != null) { // should never be null, indeed
704 if (mDirectories.getCount() <= 1) {
705 finish();
706 return;
707 }
708 int levelsUp = listOfFiles.onBrowseUp();
709 for (int i=0; i < levelsUp && mDirectories.getCount() > 1 ; i++) {
710 popDirname();
711 }
712 }
713 }
714 if (listOfFiles != null) { // should never be null, indeed
715 setFile(listOfFiles.getCurrentFile());
716 }
717 cleanSecondFragment();
718
719 }
720
721 @Override
722 protected void onSaveInstanceState(Bundle outState) {
723 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
724 Log_OC.e(TAG, "onSaveInstanceState() start");
725 super.onSaveInstanceState(outState);
726 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
727 outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
728 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
729 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
730
731 Log_OC.d(TAG, "onSaveInstanceState() end");
732 }
733
734
735
736 @Override
737 protected void onResume() {
738 super.onResume();
739 Log_OC.e(TAG, "onResume() start");
740
741 // refresh list of files
742 refreshListOfFilesFragment();
743
744 // Listen for sync messages
745 IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
746 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
747 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
748 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
749 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
750 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
751 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
752 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
753
754 // Listen for upload messages
755 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
756 mUploadFinishReceiver = new UploadFinishReceiver();
757 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
758
759 // Listen for download messages
760 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
761 downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
762 mDownloadFinishReceiver = new DownloadFinishReceiver();
763 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
764
765 Log_OC.d(TAG, "onResume() end");
766 }
767
768
769 @Override
770 protected void onPause() {
771 Log_OC.e(TAG, "onPause() start");
772 if (mSyncBroadcastReceiver != null) {
773 unregisterReceiver(mSyncBroadcastReceiver);
774 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
775 mSyncBroadcastReceiver = null;
776 }
777 if (mUploadFinishReceiver != null) {
778 unregisterReceiver(mUploadFinishReceiver);
779 mUploadFinishReceiver = null;
780 }
781 if (mDownloadFinishReceiver != null) {
782 unregisterReceiver(mDownloadFinishReceiver);
783 mDownloadFinishReceiver = null;
784 }
785
786
787 Log_OC.d(TAG, "onPause() end");
788 super.onPause();
789 }
790
791
792 @Override
793 protected Dialog onCreateDialog(int id) {
794 Dialog dialog = null;
795 AlertDialog.Builder builder;
796 switch (id) {
797 case DIALOG_SHORT_WAIT: {
798 ProgressDialog working_dialog = new ProgressDialog(this);
799 working_dialog.setMessage(getResources().getString(
800 R.string.wait_a_moment));
801 working_dialog.setIndeterminate(true);
802 working_dialog.setCancelable(false);
803 dialog = working_dialog;
804 break;
805 }
806 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
807
808
809 String[] allTheItems = { getString(R.string.actionbar_upload_files),
810 getString(R.string.actionbar_upload_from_apps) };
811
812 builder = new AlertDialog.Builder(this);
813 builder.setTitle(R.string.actionbar_upload);
814 builder.setItems(allTheItems, new DialogInterface.OnClickListener() {
815 public void onClick(DialogInterface dialog, int item) {
816 if (item == 0) {
817 // if (!mDualPane) {
818 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
819 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
820 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
821 // } else {
822 // TODO create and handle new fragment
823 // LocalFileListFragment
824 // }
825 } else if (item == 1) {
826 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
827 action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
828 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
829 ACTION_SELECT_CONTENT_FROM_APPS);
830 }
831 }
832 });
833 dialog = builder.create();
834 break;
835 }
836 case DIALOG_CERT_NOT_SAVED: {
837 builder = new AlertDialog.Builder(this);
838 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
839 builder.setCancelable(false);
840 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
841 @Override
842 public void onClick(DialogInterface dialog, int which) {
843 dialog.dismiss();
844 };
845 });
846 dialog = builder.create();
847 break;
848 }
849 default:
850 dialog = null;
851 }
852
853 return dialog;
854 }
855
856
857 /**
858 * Translates a content URI of an image to a physical path
859 * on the disk
860 * @param uri The URI to resolve
861 * @return The path to the image or null if it could not be found
862 */
863 public String getPath(Uri uri) {
864 String[] projection = { MediaStore.Images.Media.DATA };
865 Cursor cursor = managedQuery(uri, projection, null, null, null);
866 if (cursor != null) {
867 int column_index = cursor
868 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
869 cursor.moveToFirst();
870 return cursor.getString(column_index);
871 }
872 return null;
873 }
874
875 /**
876 * Pushes a directory to the drop down list
877 * @param directory to push
878 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
879 */
880 public void pushDirname(OCFile directory) {
881 if(!directory.isFolder()){
882 throw new IllegalArgumentException("Only directories may be pushed!");
883 }
884 mDirectories.insert(directory.getFileName(), 0);
885 setFile(directory);
886 }
887
888 /**
889 * Pops a directory name from the drop down list
890 * @return True, unless the stack is empty
891 */
892 public boolean popDirname() {
893 mDirectories.remove(mDirectories.getItem(0));
894 return !mDirectories.isEmpty();
895 }
896
897 // Custom array adapter to override text colors
898 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
899
900 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
901 super(ctx, view);
902 }
903
904 public View getView(int position, View convertView, ViewGroup parent) {
905 View v = super.getView(position, convertView, parent);
906
907 ((TextView) v).setTextColor(getResources().getColorStateList(
908 android.R.color.white));
909
910 fixRoot((TextView) v );
911 return v;
912 }
913
914 public View getDropDownView(int position, View convertView,
915 ViewGroup parent) {
916 View v = super.getDropDownView(position, convertView, parent);
917
918 ((TextView) v).setTextColor(getResources().getColorStateList(
919 android.R.color.white));
920
921 fixRoot((TextView) v );
922 return v;
923 }
924
925 private void fixRoot(TextView v) {
926 if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
927 v.setText(R.string.default_display_name_for_root_folder);
928 }
929 }
930
931 }
932
933 private class SyncBroadcastReceiver extends BroadcastReceiver {
934
935 /**
936 * {@link BroadcastReceiver} to enable syncing feedback in UI
937 */
938 @Override
939 public void onReceive(Context context, Intent intent) {
940 try {
941 String event = intent.getAction();
942 Log_OC.d(TAG, "Received broadcast " + event);
943 String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
944 String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
945 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
946 boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
947
948 if (sameAccount) {
949
950 if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
951 mSyncInProgress = true;
952
953 } else {
954 OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
955 OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
956
957 if (currentDir == null) {
958 // current folder was removed from the server
959 Toast.makeText( FileDisplayActivity.this,
960 String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
961 Toast.LENGTH_LONG)
962 .show();
963 browseToRoot();
964
965 } else {
966 if (currentFile == null && !getFile().isFolder()) {
967 // currently selected file was removed in the server, and now we know it
968 cleanSecondFragment();
969 currentFile = currentDir;
970 }
971
972 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
973 OCFileListFragment fileListFragment = getListOfFilesFragment();
974 if (fileListFragment != null) {
975 fileListFragment.listDirectory(currentDir);
976 }
977 }
978 setFile(currentFile);
979 }
980
981 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
982
983 if (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
984 equals(event) &&
985 /// TODO refactor and make common
986 synchResult != null && !synchResult.isSuccess() &&
987 (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
988 synchResult.isIdPRedirection() ||
989 (synchResult.isException() && synchResult.getException()
990 instanceof AuthenticatorException))) {
991
992 OwnCloudClient client = null;
993 try {
994 OwnCloudAccount ocAccount =
995 new OwnCloudAccount(getAccount(), context);
996 client = (OwnCloudClientManagerFactory.getDefaultSingleton().
997 removeClientFor(ocAccount));
998 // TODO get rid of these exceptions
999 } catch (AccountNotFoundException e) {
1000 e.printStackTrace();
1001 } catch (AuthenticatorException e) {
1002 e.printStackTrace();
1003 } catch (OperationCanceledException e) {
1004 e.printStackTrace();
1005 } catch (IOException e) {
1006 e.printStackTrace();
1007 }
1008
1009 if (client != null) {
1010 OwnCloudCredentials cred = client.getCredentials();
1011 if (cred != null) {
1012 AccountManager am = AccountManager.get(context);
1013 if (cred.authTokenExpires()) {
1014 am.invalidateAuthToken(
1015 getAccount().type,
1016 cred.getAuthToken()
1017 );
1018 } else {
1019 am.clearPassword(getAccount());
1020 }
1021 }
1022 }
1023
1024 requestCredentialsUpdate();
1025
1026 }
1027 }
1028 removeStickyBroadcast(intent);
1029 Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
1030 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
1031
1032 setBackgroundText();
1033
1034 }
1035
1036 if (synchResult != null) {
1037 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
1038 mLastSslUntrustedServerResult = synchResult;
1039 }
1040 }
1041 } catch (RuntimeException e) {
1042 // avoid app crashes after changing the serial id of RemoteOperationResult
1043 // in owncloud library with broadcast notifications pending to process
1044 removeStickyBroadcast(intent);
1045 }
1046 }
1047 }
1048
1049 /**
1050 * Show a text message on screen view for notifying user if content is
1051 * loading or folder is empty
1052 */
1053 private void setBackgroundText() {
1054 OCFileListFragment ocFileListFragment = getListOfFilesFragment();
1055 if (ocFileListFragment != null) {
1056 int message = R.string.file_list_loading;
1057 if (!mSyncInProgress) {
1058 // In case file list is empty
1059 message = R.string.file_list_empty;
1060 }
1061 ocFileListFragment.setMessageForEmptyList(getString(message));
1062 } else {
1063 Log.e(TAG, "OCFileListFragment is null");
1064 }
1065 }
1066
1067 /**
1068 * Once the file upload has finished -> update view
1069 */
1070 private class UploadFinishReceiver extends BroadcastReceiver {
1071 /**
1072 * Once the file upload has finished -> update view
1073 * @author David A. Velasco
1074 * {@link BroadcastReceiver} to enable upload feedback in UI
1075 */
1076 @Override
1077 public void onReceive(Context context, Intent intent) {
1078 try {
1079 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1080 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
1081 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
1082 OCFile currentDir = getCurrentDir();
1083 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
1084 (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
1085
1086 if (sameAccount && isDescendant) {
1087 refreshListOfFilesFragment();
1088 }
1089
1090 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
1091 boolean renamedInUpload = getFile().getRemotePath().
1092 equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
1093 boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
1094 renamedInUpload;
1095 FileFragment details = getSecondFragment();
1096 boolean detailFragmentIsShown = (details != null &&
1097 details instanceof FileDetailFragment);
1098
1099 if (sameAccount && sameFile && detailFragmentIsShown) {
1100 if (uploadWasFine) {
1101 setFile(getStorageManager().getFileByPath(uploadedRemotePath));
1102 }
1103 if (renamedInUpload) {
1104 String newName = (new File(uploadedRemotePath)).getName();
1105 Toast msg = Toast.makeText(
1106 context,
1107 String.format(
1108 getString(R.string.filedetails_renamed_in_upload_msg),
1109 newName),
1110 Toast.LENGTH_LONG);
1111 msg.show();
1112 }
1113 if (uploadWasFine || getFile().fileExists()) {
1114 ((FileDetailFragment)details).updateFileDetails(false, true);
1115 } else {
1116 cleanSecondFragment();
1117 }
1118
1119 // Force the preview if the file is an image
1120 if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
1121 startImagePreview(getFile());
1122 } // TODO what about other kind of previews?
1123 }
1124
1125 } finally {
1126 if (intent != null) {
1127 removeStickyBroadcast(intent);
1128 }
1129 }
1130
1131 }
1132
1133 }
1134
1135
1136 /**
1137 * Class waiting for broadcast events from the {@link FielDownloader} service.
1138 *
1139 * Updates the UI when a download is started or finished, provided that it is relevant for the
1140 * current folder.
1141 */
1142 private class DownloadFinishReceiver extends BroadcastReceiver {
1143 @Override
1144 public void onReceive(Context context, Intent intent) {
1145 try {
1146 boolean sameAccount = isSameAccount(context, intent);
1147 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1148 boolean isDescendant = isDescendant(downloadedRemotePath);
1149
1150 if (sameAccount && isDescendant) {
1151 refreshListOfFilesFragment();
1152 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1153 }
1154
1155 if (mWaitingToSend != null) {
1156 mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath()); // Update the file to send
1157 if (mWaitingToSend.isDown()) {
1158 sendDownloadedFile();
1159 }
1160 }
1161
1162 } finally {
1163 if (intent != null) {
1164 removeStickyBroadcast(intent);
1165 }
1166 }
1167 }
1168
1169 private boolean isDescendant(String downloadedRemotePath) {
1170 OCFile currentDir = getCurrentDir();
1171 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
1172 }
1173
1174 private boolean isSameAccount(Context context, Intent intent) {
1175 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1176 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1177 }
1178 }
1179
1180
1181 public void browseToRoot() {
1182 OCFileListFragment listOfFiles = getListOfFilesFragment();
1183 if (listOfFiles != null) { // should never be null, indeed
1184 while (mDirectories.getCount() > 1) {
1185 popDirname();
1186 }
1187 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1188 listOfFiles.listDirectory(root);
1189 setFile(listOfFiles.getCurrentFile());
1190 startSyncFolderOperation(root);
1191 }
1192 cleanSecondFragment();
1193 }
1194
1195
1196 public void browseTo(OCFile folder) {
1197 if (folder == null || !folder.isFolder()) {
1198 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1199 }
1200 OCFileListFragment listOfFiles = getListOfFilesFragment();
1201 if (listOfFiles != null) {
1202 setNavigationListWithFolder(folder);
1203 listOfFiles.listDirectory(folder);
1204 setFile(listOfFiles.getCurrentFile());
1205 startSyncFolderOperation(folder);
1206 } else {
1207 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1208 }
1209 cleanSecondFragment();
1210 }
1211
1212
1213 /**
1214 * {@inheritDoc}
1215 *
1216 * Updates action bar and second fragment, if in dual pane mode.
1217 */
1218 @Override
1219 public void onBrowsedDownTo(OCFile directory) {
1220 pushDirname(directory);
1221 cleanSecondFragment();
1222
1223 // Sync Folder
1224 startSyncFolderOperation(directory);
1225
1226 }
1227
1228 /**
1229 * Shows the information of the {@link OCFile} received as a
1230 * parameter in the second fragment.
1231 *
1232 * @param file {@link OCFile} whose details will be shown
1233 */
1234 @Override
1235 public void showDetails(OCFile file) {
1236 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1237 setSecondFragment(detailFragment);
1238 updateFragmentsVisibility(true);
1239 updateNavigationElementsInActionBar(file);
1240 setFile(file);
1241 }
1242
1243
1244 /**
1245 * TODO
1246 */
1247 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1248 ActionBar actionBar = getSupportActionBar();
1249 if (chosenFile == null || mDualPane) {
1250 // only list of files - set for browsing through folders
1251 OCFile currentDir = getCurrentDir();
1252 boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
1253 actionBar.setDisplayHomeAsUpEnabled(noRoot);
1254 actionBar.setDisplayShowTitleEnabled(!noRoot);
1255 if (!noRoot) {
1256 actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
1257 }
1258 actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
1259 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1260
1261 } else {
1262 actionBar.setDisplayHomeAsUpEnabled(true);
1263 actionBar.setDisplayShowTitleEnabled(true);
1264 actionBar.setTitle(chosenFile.getFileName());
1265 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1266 }
1267 }
1268
1269
1270 @Override
1271 protected ServiceConnection newTransferenceServiceConnection() {
1272 return new ListServiceConnection();
1273 }
1274
1275 /** Defines callbacks for service binding, passed to bindService() */
1276 private class ListServiceConnection implements ServiceConnection {
1277
1278 @Override
1279 public void onServiceConnected(ComponentName component, IBinder service) {
1280 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1281 Log_OC.d(TAG, "Download service connected");
1282 mDownloaderBinder = (FileDownloaderBinder) service;
1283 if (mWaitingToPreview != null)
1284 if (getStorageManager() != null) {
1285 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file
1286 if (!mWaitingToPreview.isDown()) {
1287 requestForDownload();
1288 }
1289 }
1290
1291 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1292 Log_OC.d(TAG, "Upload service connected");
1293 mUploaderBinder = (FileUploaderBinder) service;
1294 } else {
1295 return;
1296 }
1297 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1298 OCFileListFragment listOfFiles = getListOfFilesFragment();
1299 if (listOfFiles != null) {
1300 listOfFiles.listDirectory();
1301 }
1302 FileFragment secondFragment = getSecondFragment();
1303 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1304 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1305 detailFragment.listenForTransferProgress();
1306 detailFragment.updateFileDetails(false, false);
1307 }
1308 }
1309
1310 @Override
1311 public void onServiceDisconnected(ComponentName component) {
1312 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1313 Log_OC.d(TAG, "Download service disconnected");
1314 mDownloaderBinder = null;
1315 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1316 Log_OC.d(TAG, "Upload service disconnected");
1317 mUploaderBinder = null;
1318 }
1319 }
1320 };
1321
1322
1323
1324 /**
1325 * Launch an intent to request the PIN code to the user before letting him use the app
1326 */
1327 private void requestPinCode() {
1328 boolean pinStart = false;
1329 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1330 pinStart = appPrefs.getBoolean("set_pincode", false);
1331 if (pinStart) {
1332 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1333 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1334 startActivity(i);
1335 }
1336 }
1337
1338
1339 @Override
1340 public void onSavedCertificate() {
1341 startSyncFolderOperation(getCurrentDir());
1342 }
1343
1344
1345 @Override
1346 public void onFailedSavingCertificate() {
1347 showDialog(DIALOG_CERT_NOT_SAVED);
1348 }
1349
1350 @Override
1351 public void onCancelCertificate() {
1352 // nothing to do
1353 }
1354
1355 /**
1356 * Updates the view associated to the activity after the finish of some operation over files
1357 * in the current account.
1358 *
1359 * @param operation Removal operation performed.
1360 * @param result Result of the removal.
1361 */
1362 @Override
1363 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1364 super.onRemoteOperationFinish(operation, result);
1365
1366 if (operation instanceof RemoveFileOperation) {
1367 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1368
1369 } else if (operation instanceof RenameFileOperation) {
1370 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1371
1372 } else if (operation instanceof SynchronizeFileOperation) {
1373 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1374
1375 } else if (operation instanceof CreateFolderOperation) {
1376 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1377
1378 } else if (operation instanceof CreateShareOperation) {
1379 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1380
1381 } else if (operation instanceof UnshareLinkOperation) {
1382 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
1383
1384 } else if (operation instanceof MoveFileOperation) {
1385 onMoveFileOperationFinish((MoveFileOperation)operation, result);
1386 }
1387
1388 }
1389
1390
1391 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
1392 if (result.isSuccess()) {
1393 refreshShowDetails();
1394 refreshListOfFilesFragment();
1395 }
1396 }
1397
1398
1399 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
1400 if (result.isSuccess()) {
1401 refreshShowDetails();
1402 refreshListOfFilesFragment();
1403
1404 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
1405 cleanSecondFragment();
1406 refreshListOfFilesFragment();
1407 }
1408 }
1409
1410 private void refreshShowDetails() {
1411 FileFragment details = getSecondFragment();
1412 if (details != null) {
1413 OCFile file = details.getFile();
1414 if (file != null) {
1415 file = getStorageManager().getFileByPath(file.getRemotePath());
1416 if (details instanceof PreviewMediaFragment) {
1417 // Refresh OCFile of the fragment
1418 ((PreviewMediaFragment) details).updateFile(file);
1419 } else {
1420 showDetails(file);
1421 }
1422 }
1423 invalidateOptionsMenu();
1424 }
1425 }
1426
1427 /**
1428 * Updates the view associated to the activity after the finish of an operation trying to remove a
1429 * file.
1430 *
1431 * @param operation Removal operation performed.
1432 * @param result Result of the removal.
1433 */
1434 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1435 dismissLoadingDialog();
1436
1437 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1438 Toast.LENGTH_LONG);
1439 msg.show();
1440
1441 if (result.isSuccess()) {
1442 OCFile removedFile = operation.getFile();
1443 FileFragment second = getSecondFragment();
1444 if (second != null && removedFile.equals(second.getFile())) {
1445 if (second instanceof PreviewMediaFragment) {
1446 ((PreviewMediaFragment)second).stopPreview(true);
1447 }
1448 setFile(getStorageManager().getFileById(removedFile.getParentId()));
1449 cleanSecondFragment();
1450 }
1451 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1452 refreshListOfFilesFragment();
1453 }
1454 invalidateOptionsMenu();
1455 } else {
1456 if (result.isSslRecoverableException()) {
1457 mLastSslUntrustedServerResult = result;
1458 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1459 }
1460 }
1461 }
1462
1463
1464 /**
1465 * Updates the view associated to the activity after the finish of an operation trying to move a
1466 * file.
1467 *
1468 * @param operation Move operation performed.
1469 * @param result Result of the move operation.
1470 */
1471 private void onMoveFileOperationFinish(MoveFileOperation operation, RemoteOperationResult result) {
1472 if (result.isSuccess()) {
1473 dismissLoadingDialog();
1474 refreshListOfFilesFragment();
1475 } else {
1476 dismissLoadingDialog();
1477 try {
1478 Toast msg = Toast.makeText(FileDisplayActivity.this,
1479 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1480 Toast.LENGTH_LONG);
1481 msg.show();
1482
1483 } catch (NotFoundException e) {
1484 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1485 }
1486 }
1487 }
1488
1489
1490 /**
1491 * Updates the view associated to the activity after the finish of an operation trying to rename a
1492 * file.
1493 *
1494 * @param operation Renaming operation performed.
1495 * @param result Result of the renaming.
1496 */
1497 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1498 dismissLoadingDialog();
1499 OCFile renamedFile = operation.getFile();
1500 if (result.isSuccess()) {
1501 FileFragment details = getSecondFragment();
1502 if (details != null) {
1503 if (details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1504 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1505 showDetails(renamedFile);
1506
1507 } else if (details instanceof PreviewMediaFragment && renamedFile.equals(details.getFile())) {
1508 ((PreviewMediaFragment) details).updateFile(renamedFile);
1509 if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
1510 int position = ((PreviewMediaFragment)details).getPosition();
1511 startMediaPreview(renamedFile, position, true);
1512 } else {
1513 getFileOperationsHelper().openFile(renamedFile);
1514 }
1515 }
1516 }
1517
1518 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1519 refreshListOfFilesFragment();
1520 }
1521
1522 } else {
1523 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1524 Toast.LENGTH_LONG);
1525 msg.show();
1526
1527 if (result.isSslRecoverableException()) {
1528 mLastSslUntrustedServerResult = result;
1529 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1530 }
1531 }
1532 }
1533
1534 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1535 dismissLoadingDialog();
1536 OCFile syncedFile = operation.getLocalFile();
1537 if (!result.isSuccess()) {
1538 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1539 Intent i = new Intent(this, ConflictsResolveActivity.class);
1540 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1541 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1542 startActivity(i);
1543
1544 }
1545
1546 } else {
1547 if (operation.transferWasRequested()) {
1548 onTransferStateChanged(syncedFile, true, true);
1549
1550 } else {
1551 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1552 Toast.LENGTH_LONG);
1553 msg.show();
1554 }
1555 }
1556 }
1557
1558 /**
1559 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1560 *
1561 * @param operation Creation operation performed.
1562 * @param result Result of the creation.
1563 */
1564 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1565 if (result.isSuccess()) {
1566 dismissLoadingDialog();
1567 refreshListOfFilesFragment();
1568 } else {
1569 dismissLoadingDialog();
1570 try {
1571 Toast msg = Toast.makeText(FileDisplayActivity.this,
1572 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1573 Toast.LENGTH_LONG);
1574 msg.show();
1575
1576 } catch (NotFoundException e) {
1577 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1578 }
1579 }
1580 }
1581
1582
1583 /**
1584 * {@inheritDoc}
1585 */
1586 @Override
1587 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1588 refreshListOfFilesFragment();
1589 FileFragment details = getSecondFragment();
1590 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1591 if (downloading || uploading) {
1592 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1593 } else {
1594 if (!file.fileExists()) {
1595 cleanSecondFragment();
1596 } else {
1597 ((FileDetailFragment)details).updateFileDetails(false, true);
1598 }
1599 }
1600 }
1601
1602 }
1603
1604
1605 private void requestForDownload() {
1606 Account account = getAccount();
1607 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1608 Intent i = new Intent(this, FileDownloader.class);
1609 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1610 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1611 startService(i);
1612 }
1613 }
1614
1615
1616 private OCFile getCurrentDir() {
1617 OCFile file = getFile();
1618 if (file != null) {
1619 if (file.isFolder()) {
1620 return file;
1621 } else if (getStorageManager() != null) {
1622 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
1623 return getStorageManager().getFileByPath(parentPath);
1624 }
1625 }
1626 return null;
1627 }
1628
1629 public void startSyncFolderOperation(OCFile folder) {
1630 long currentSyncTime = System.currentTimeMillis();
1631
1632 mSyncInProgress = true;
1633
1634 // perform folder synchronization
1635 RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
1636 currentSyncTime,
1637 false,
1638 getFileOperationsHelper().isSharedSupported(),
1639 getStorageManager(),
1640 getAccount(),
1641 getApplicationContext()
1642 );
1643 synchFolderOp.execute(getAccount(), this, null, null);
1644
1645 setSupportProgressBarIndeterminateVisibility(true);
1646
1647 setBackgroundText();
1648 }
1649
1650 /**
1651 * Show untrusted cert dialog
1652 */
1653 public void showUntrustedCertDialog(RemoteOperationResult result) {
1654 // Show a dialog with the certificate info
1655 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());
1656 FragmentManager fm = getSupportFragmentManager();
1657 FragmentTransaction ft = fm.beginTransaction();
1658 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
1659 }
1660
1661 private void requestForDownload(OCFile file) {
1662 Account account = getAccount();
1663 if (!mDownloaderBinder.isDownloading(account, file)) {
1664 Intent i = new Intent(this, FileDownloader.class);
1665 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1666 i.putExtra(FileDownloader.EXTRA_FILE, file);
1667 startService(i);
1668 }
1669 }
1670
1671 private void sendDownloadedFile(){
1672 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
1673 mWaitingToSend = null;
1674 }
1675
1676
1677 /**
1678 * Requests the download of the received {@link OCFile} , updates the UI
1679 * to monitor the download progress and prepares the activity to send the file
1680 * when the download finishes.
1681 *
1682 * @param file {@link OCFile} to download and preview.
1683 */
1684 public void startDownloadForSending(OCFile file) {
1685 mWaitingToSend = file;
1686 requestForDownload(mWaitingToSend);
1687 boolean hasSecondFragment = (getSecondFragment()!= null);
1688 updateFragmentsVisibility(hasSecondFragment);
1689 }
1690
1691 /**
1692 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1693 *
1694 * @param file Image {@link OCFile} to show.
1695 */
1696 public void startImagePreview(OCFile file) {
1697 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1698 showDetailsIntent.putExtra(EXTRA_FILE, file);
1699 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1700 startActivity(showDetailsIntent);
1701
1702 }
1703
1704 /**
1705 * Stars the preview of an already down media {@link OCFile}.
1706 *
1707 * @param file Media {@link OCFile} to preview.
1708 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1709 * @param autoplay When 'true', the playback will start without user interactions.
1710 */
1711 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1712 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1713 setSecondFragment(mediaFragment);
1714 updateFragmentsVisibility(true);
1715 updateNavigationElementsInActionBar(file);
1716 setFile(file);
1717 }
1718
1719 /**
1720 * Requests the download of the received {@link OCFile} , updates the UI
1721 * to monitor the download progress and prepares the activity to preview
1722 * or open the file when the download finishes.
1723 *
1724 * @param file {@link OCFile} to download and preview.
1725 */
1726 public void startDownloadForPreview(OCFile file) {
1727 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1728 setSecondFragment(detailFragment);
1729 mWaitingToPreview = file;
1730 requestForDownload();
1731 updateFragmentsVisibility(true);
1732 updateNavigationElementsInActionBar(file);
1733 setFile(file);
1734 }
1735
1736
1737 public void cancelTransference(OCFile file) {
1738 getFileOperationsHelper().cancelTransference(file);
1739 if (mWaitingToPreview != null &&
1740 mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
1741 mWaitingToPreview = null;
1742 }
1743 if (mWaitingToSend != null &&
1744 mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
1745 mWaitingToSend = null;
1746 }
1747 onTransferStateChanged(file, false, false);
1748 }
1749
1750 @Override
1751 public void onRefresh() {
1752 OCFileListFragment listOfFiles = getListOfFilesFragment();
1753 if (listOfFiles != null) {
1754 OCFile folder = listOfFiles.getCurrentFile();
1755 if (folder != null) {
1756 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1757 listDirectory(mFile);*/
1758 startSyncFolderOperation(folder);
1759 }
1760 }
1761 }
1762
1763 private void sortByDate(boolean ascending){
1764 getListOfFilesFragment().sortByDate(ascending);
1765 }
1766
1767 private void sortBySize(boolean ascending){
1768 getListOfFilesFragment().sortBySize(ascending);
1769 }
1770
1771 private void sortByName(boolean ascending){
1772 getListOfFilesFragment().sortByName(ascending);
1773 }
1774
1775 }