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