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