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