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