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