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