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