da6eb527c1dd9e8218dfeff5772da8d8f8185054
[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 getFileOperationsHelper().moveFile(folderToMoveAt, getCurrentDir());
649 }
650
651 @Override
652 public void onBackPressed() {
653 OCFileListFragment listOfFiles = getListOfFilesFragment();
654 if (mDualPane || getSecondFragment() == null) {
655 if (listOfFiles != null) { // should never be null, indeed
656 if (mDirectories.getCount() <= 1) {
657 finish();
658 return;
659 }
660 int levelsUp = listOfFiles.onBrowseUp();
661 for (int i=0; i < levelsUp && mDirectories.getCount() > 1 ; i++) {
662 popDirname();
663 }
664 }
665 }
666 if (listOfFiles != null) { // should never be null, indeed
667 setFile(listOfFiles.getCurrentFile());
668 }
669 cleanSecondFragment();
670
671 }
672
673 @Override
674 protected void onSaveInstanceState(Bundle outState) {
675 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
676 Log_OC.e(TAG, "onSaveInstanceState() start");
677 super.onSaveInstanceState(outState);
678 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
679 outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
680 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
681 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);
682
683 Log_OC.d(TAG, "onSaveInstanceState() end");
684 }
685
686
687
688 @Override
689 protected void onResume() {
690 super.onResume();
691 Log_OC.e(TAG, "onResume() start");
692
693 // refresh list of files
694 refreshListOfFilesFragment();
695
696 // Listen for sync messages
697 IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
698 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
699 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
700 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
701 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
702 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
703 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
704 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
705
706 // Listen for upload messages
707 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
708 mUploadFinishReceiver = new UploadFinishReceiver();
709 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
710
711 // Listen for download messages
712 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
713 downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
714 mDownloadFinishReceiver = new DownloadFinishReceiver();
715 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
716
717 Log_OC.d(TAG, "onResume() end");
718 }
719
720
721 @Override
722 protected void onPause() {
723 Log_OC.e(TAG, "onPause() start");
724 if (mSyncBroadcastReceiver != null) {
725 unregisterReceiver(mSyncBroadcastReceiver);
726 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
727 mSyncBroadcastReceiver = null;
728 }
729 if (mUploadFinishReceiver != null) {
730 unregisterReceiver(mUploadFinishReceiver);
731 mUploadFinishReceiver = null;
732 }
733 if (mDownloadFinishReceiver != null) {
734 unregisterReceiver(mDownloadFinishReceiver);
735 mDownloadFinishReceiver = null;
736 }
737
738
739 Log_OC.d(TAG, "onPause() end");
740 super.onPause();
741 }
742
743
744 @Override
745 protected Dialog onCreateDialog(int id) {
746 Dialog dialog = null;
747 AlertDialog.Builder builder;
748 switch (id) {
749 case DIALOG_SHORT_WAIT: {
750 ProgressDialog working_dialog = new ProgressDialog(this);
751 working_dialog.setMessage(getResources().getString(
752 R.string.wait_a_moment));
753 working_dialog.setIndeterminate(true);
754 working_dialog.setCancelable(false);
755 dialog = working_dialog;
756 break;
757 }
758 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
759
760
761 String[] allTheItems = { getString(R.string.actionbar_upload_files),
762 getString(R.string.actionbar_upload_from_apps) };
763
764 builder = new AlertDialog.Builder(this);
765 builder.setTitle(R.string.actionbar_upload);
766 builder.setItems(allTheItems, new DialogInterface.OnClickListener() {
767 public void onClick(DialogInterface dialog, int item) {
768 if (item == 0) {
769 // if (!mDualPane) {
770 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
771 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
772 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
773 // } else {
774 // TODO create and handle new fragment
775 // LocalFileListFragment
776 // }
777 } else if (item == 1) {
778 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
779 action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
780 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
781 ACTION_SELECT_CONTENT_FROM_APPS);
782 }
783 }
784 });
785 dialog = builder.create();
786 break;
787 }
788 case DIALOG_CERT_NOT_SAVED: {
789 builder = new AlertDialog.Builder(this);
790 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
791 builder.setCancelable(false);
792 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
793 @Override
794 public void onClick(DialogInterface dialog, int which) {
795 dialog.dismiss();
796 };
797 });
798 dialog = builder.create();
799 break;
800 }
801 default:
802 dialog = null;
803 }
804
805 return dialog;
806 }
807
808
809 /**
810 * Translates a content URI of an image to a physical path
811 * on the disk
812 * @param uri The URI to resolve
813 * @return The path to the image or null if it could not be found
814 */
815 public String getPath(Uri uri) {
816 String[] projection = { MediaStore.Images.Media.DATA };
817 Cursor cursor = managedQuery(uri, projection, null, null, null);
818 if (cursor != null) {
819 int column_index = cursor
820 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
821 cursor.moveToFirst();
822 return cursor.getString(column_index);
823 }
824 return null;
825 }
826
827 /**
828 * Pushes a directory to the drop down list
829 * @param directory to push
830 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
831 */
832 public void pushDirname(OCFile directory) {
833 if(!directory.isFolder()){
834 throw new IllegalArgumentException("Only directories may be pushed!");
835 }
836 mDirectories.insert(directory.getFileName(), 0);
837 setFile(directory);
838 }
839
840 /**
841 * Pops a directory name from the drop down list
842 * @return True, unless the stack is empty
843 */
844 public boolean popDirname() {
845 mDirectories.remove(mDirectories.getItem(0));
846 return !mDirectories.isEmpty();
847 }
848
849 // Custom array adapter to override text colors
850 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
851
852 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
853 super(ctx, view);
854 }
855
856 public View getView(int position, View convertView, ViewGroup parent) {
857 View v = super.getView(position, convertView, parent);
858
859 ((TextView) v).setTextColor(getResources().getColorStateList(
860 android.R.color.white));
861
862 fixRoot((TextView) v );
863 return v;
864 }
865
866 public View getDropDownView(int position, View convertView,
867 ViewGroup parent) {
868 View v = super.getDropDownView(position, convertView, parent);
869
870 ((TextView) v).setTextColor(getResources().getColorStateList(
871 android.R.color.white));
872
873 fixRoot((TextView) v );
874 return v;
875 }
876
877 private void fixRoot(TextView v) {
878 if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
879 v.setText(R.string.default_display_name_for_root_folder);
880 }
881 }
882
883 }
884
885 private class SyncBroadcastReceiver extends BroadcastReceiver {
886
887 /**
888 * {@link BroadcastReceiver} to enable syncing feedback in UI
889 */
890 @Override
891 public void onReceive(Context context, Intent intent) {
892 try {
893 String event = intent.getAction();
894 Log_OC.d(TAG, "Received broadcast " + event);
895 String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
896 String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
897 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
898 boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
899
900 if (sameAccount) {
901
902 if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
903 mSyncInProgress = true;
904
905 } else {
906 OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
907 OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
908
909 if (currentDir == null) {
910 // current folder was removed from the server
911 Toast.makeText( FileDisplayActivity.this,
912 String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
913 Toast.LENGTH_LONG)
914 .show();
915 browseToRoot();
916
917 } else {
918 if (currentFile == null && !getFile().isFolder()) {
919 // currently selected file was removed in the server, and now we know it
920 cleanSecondFragment();
921 currentFile = currentDir;
922 }
923
924 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
925 OCFileListFragment fileListFragment = getListOfFilesFragment();
926 if (fileListFragment != null) {
927 fileListFragment.listDirectory(currentDir);
928 }
929 }
930 setFile(currentFile);
931 }
932
933 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
934
935 if (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
936 equals(event) &&
937 /// TODO refactor and make common
938 synchResult != null && !synchResult.isSuccess() &&
939 (synchResult.getCode() == ResultCode.UNAUTHORIZED ||
940 synchResult.isIdPRedirection() ||
941 (synchResult.isException() && synchResult.getException()
942 instanceof AuthenticatorException))) {
943
944 OwnCloudClient client = null;
945 try {
946 OwnCloudAccount ocAccount =
947 new OwnCloudAccount(getAccount(), context);
948 client = (OwnCloudClientManagerFactory.getDefaultSingleton().
949 removeClientFor(ocAccount));
950 // TODO get rid of these exceptions
951 } catch (AccountNotFoundException e) {
952 e.printStackTrace();
953 } catch (AuthenticatorException e) {
954 e.printStackTrace();
955 } catch (OperationCanceledException e) {
956 e.printStackTrace();
957 } catch (IOException e) {
958 e.printStackTrace();
959 }
960
961 if (client != null) {
962 OwnCloudCredentials cred = client.getCredentials();
963 if (cred != null) {
964 AccountManager am = AccountManager.get(context);
965 if (cred.authTokenExpires()) {
966 am.invalidateAuthToken(
967 getAccount().type,
968 cred.getAuthToken()
969 );
970 } else {
971 am.clearPassword(getAccount());
972 }
973 }
974 }
975
976 requestCredentialsUpdate();
977
978 }
979 }
980 removeStickyBroadcast(intent);
981 Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
982 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
983
984 setBackgroundText();
985
986 }
987
988 if (synchResult != null) {
989 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
990 mLastSslUntrustedServerResult = synchResult;
991 }
992 }
993 } catch (RuntimeException e) {
994 // avoid app crashes after changing the serial id of RemoteOperationResult
995 // in owncloud library with broadcast notifications pending to process
996 removeStickyBroadcast(intent);
997 }
998 }
999 }
1000
1001 /**
1002 * Show a text message on screen view for notifying user if content is
1003 * loading or folder is empty
1004 */
1005 private void setBackgroundText() {
1006 OCFileListFragment ocFileListFragment = getListOfFilesFragment();
1007 if (ocFileListFragment != null) {
1008 int message = R.string.file_list_loading;
1009 if (!mSyncInProgress) {
1010 // In case file list is empty
1011 message = R.string.file_list_empty;
1012 }
1013 ocFileListFragment.setMessageForEmptyList(getString(message));
1014 } else {
1015 Log.e(TAG, "OCFileListFragment is null");
1016 }
1017 }
1018
1019 /**
1020 * Once the file upload has finished -> update view
1021 */
1022 private class UploadFinishReceiver extends BroadcastReceiver {
1023 /**
1024 * Once the file upload has finished -> update view
1025 * @author David A. Velasco
1026 * {@link BroadcastReceiver} to enable upload feedback in UI
1027 */
1028 @Override
1029 public void onReceive(Context context, Intent intent) {
1030 try {
1031 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1032 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
1033 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
1034 OCFile currentDir = getCurrentDir();
1035 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) &&
1036 (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
1037
1038 if (sameAccount && isDescendant) {
1039 refreshListOfFilesFragment();
1040 }
1041
1042 boolean uploadWasFine = intent.getBooleanExtra(FileUploader.EXTRA_UPLOAD_RESULT, false);
1043 boolean renamedInUpload = getFile().getRemotePath().
1044 equals(intent.getStringExtra(FileUploader.EXTRA_OLD_REMOTE_PATH));
1045 boolean sameFile = getFile().getRemotePath().equals(uploadedRemotePath) ||
1046 renamedInUpload;
1047 FileFragment details = getSecondFragment();
1048 boolean detailFragmentIsShown = (details != null &&
1049 details instanceof FileDetailFragment);
1050
1051 if (sameAccount && sameFile && detailFragmentIsShown) {
1052 if (uploadWasFine) {
1053 setFile(getStorageManager().getFileByPath(uploadedRemotePath));
1054 }
1055 if (renamedInUpload) {
1056 String newName = (new File(uploadedRemotePath)).getName();
1057 Toast msg = Toast.makeText(
1058 context,
1059 String.format(
1060 getString(R.string.filedetails_renamed_in_upload_msg),
1061 newName),
1062 Toast.LENGTH_LONG);
1063 msg.show();
1064 }
1065 if (uploadWasFine || getFile().fileExists()) {
1066 ((FileDetailFragment)details).updateFileDetails(false, true);
1067 } else {
1068 cleanSecondFragment();
1069 }
1070
1071 // Force the preview if the file is an image
1072 if (uploadWasFine && PreviewImageFragment.canBePreviewed(getFile())) {
1073 startImagePreview(getFile());
1074 } // TODO what about other kind of previews?
1075 }
1076
1077 } finally {
1078 if (intent != null) {
1079 removeStickyBroadcast(intent);
1080 }
1081 }
1082
1083 }
1084
1085 }
1086
1087
1088 /**
1089 * Class waiting for broadcast events from the {@link FielDownloader} service.
1090 *
1091 * Updates the UI when a download is started or finished, provided that it is relevant for the
1092 * current folder.
1093 */
1094 private class DownloadFinishReceiver extends BroadcastReceiver {
1095 @Override
1096 public void onReceive(Context context, Intent intent) {
1097 try {
1098 boolean sameAccount = isSameAccount(context, intent);
1099 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1100 boolean isDescendant = isDescendant(downloadedRemotePath);
1101
1102 if (sameAccount && isDescendant) {
1103 refreshListOfFilesFragment();
1104 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1105 }
1106
1107 if (mWaitingToSend != null) {
1108 mWaitingToSend = getStorageManager().getFileByPath(mWaitingToSend.getRemotePath()); // Update the file to send
1109 if (mWaitingToSend.isDown()) {
1110 sendDownloadedFile();
1111 }
1112 }
1113
1114 } finally {
1115 if (intent != null) {
1116 removeStickyBroadcast(intent);
1117 }
1118 }
1119 }
1120
1121 private boolean isDescendant(String downloadedRemotePath) {
1122 OCFile currentDir = getCurrentDir();
1123 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
1124 }
1125
1126 private boolean isSameAccount(Context context, Intent intent) {
1127 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1128 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1129 }
1130 }
1131
1132
1133 public void browseToRoot() {
1134 OCFileListFragment listOfFiles = getListOfFilesFragment();
1135 if (listOfFiles != null) { // should never be null, indeed
1136 while (mDirectories.getCount() > 1) {
1137 popDirname();
1138 }
1139 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1140 listOfFiles.listDirectory(root);
1141 setFile(listOfFiles.getCurrentFile());
1142 startSyncFolderOperation(root);
1143 }
1144 cleanSecondFragment();
1145 }
1146
1147
1148 public void browseTo(OCFile folder) {
1149 if (folder == null || !folder.isFolder()) {
1150 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1151 }
1152 OCFileListFragment listOfFiles = getListOfFilesFragment();
1153 if (listOfFiles != null) {
1154 setNavigationListWithFolder(folder);
1155 listOfFiles.listDirectory(folder);
1156 setFile(listOfFiles.getCurrentFile());
1157 startSyncFolderOperation(folder);
1158 } else {
1159 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1160 }
1161 cleanSecondFragment();
1162 }
1163
1164
1165 /**
1166 * {@inheritDoc}
1167 *
1168 * Updates action bar and second fragment, if in dual pane mode.
1169 */
1170 @Override
1171 public void onBrowsedDownTo(OCFile directory) {
1172 pushDirname(directory);
1173 cleanSecondFragment();
1174
1175 // Sync Folder
1176 startSyncFolderOperation(directory);
1177
1178 }
1179
1180 /**
1181 * Shows the information of the {@link OCFile} received as a
1182 * parameter in the second fragment.
1183 *
1184 * @param file {@link OCFile} whose details will be shown
1185 */
1186 @Override
1187 public void showDetails(OCFile file) {
1188 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1189 setSecondFragment(detailFragment);
1190 updateFragmentsVisibility(true);
1191 updateNavigationElementsInActionBar(file);
1192 setFile(file);
1193 }
1194
1195
1196 /**
1197 * TODO
1198 */
1199 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1200 ActionBar actionBar = getSupportActionBar();
1201 if (chosenFile == null || mDualPane) {
1202 // only list of files - set for browsing through folders
1203 OCFile currentDir = getCurrentDir();
1204 boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
1205 actionBar.setDisplayHomeAsUpEnabled(noRoot);
1206 actionBar.setDisplayShowTitleEnabled(!noRoot);
1207 if (!noRoot) {
1208 actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
1209 }
1210 actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
1211 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1212
1213 } else {
1214 actionBar.setDisplayHomeAsUpEnabled(true);
1215 actionBar.setDisplayShowTitleEnabled(true);
1216 actionBar.setTitle(chosenFile.getFileName());
1217 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1218 }
1219 }
1220
1221
1222 @Override
1223 protected ServiceConnection newTransferenceServiceConnection() {
1224 return new ListServiceConnection();
1225 }
1226
1227 /** Defines callbacks for service binding, passed to bindService() */
1228 private class ListServiceConnection implements ServiceConnection {
1229
1230 @Override
1231 public void onServiceConnected(ComponentName component, IBinder service) {
1232 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1233 Log_OC.d(TAG, "Download service connected");
1234 mDownloaderBinder = (FileDownloaderBinder) service;
1235 if (mWaitingToPreview != null)
1236 if (getStorageManager() != null) {
1237 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file
1238 if (!mWaitingToPreview.isDown()) {
1239 requestForDownload();
1240 }
1241 }
1242
1243 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1244 Log_OC.d(TAG, "Upload service connected");
1245 mUploaderBinder = (FileUploaderBinder) service;
1246 } else {
1247 return;
1248 }
1249 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1250 OCFileListFragment listOfFiles = getListOfFilesFragment();
1251 if (listOfFiles != null) {
1252 listOfFiles.listDirectory();
1253 }
1254 FileFragment secondFragment = getSecondFragment();
1255 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1256 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1257 detailFragment.listenForTransferProgress();
1258 detailFragment.updateFileDetails(false, false);
1259 }
1260 }
1261
1262 @Override
1263 public void onServiceDisconnected(ComponentName component) {
1264 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1265 Log_OC.d(TAG, "Download service disconnected");
1266 mDownloaderBinder = null;
1267 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1268 Log_OC.d(TAG, "Upload service disconnected");
1269 mUploaderBinder = null;
1270 }
1271 }
1272 };
1273
1274
1275
1276 /**
1277 * Launch an intent to request the PIN code to the user before letting him use the app
1278 */
1279 private void requestPinCode() {
1280 boolean pinStart = false;
1281 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1282 pinStart = appPrefs.getBoolean("set_pincode", false);
1283 if (pinStart) {
1284 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1285 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1286 startActivity(i);
1287 }
1288 }
1289
1290
1291 @Override
1292 public void onSavedCertificate() {
1293 startSyncFolderOperation(getCurrentDir());
1294 }
1295
1296
1297 @Override
1298 public void onFailedSavingCertificate() {
1299 showDialog(DIALOG_CERT_NOT_SAVED);
1300 }
1301
1302 @Override
1303 public void onCancelCertificate() {
1304 // nothing to do
1305 }
1306
1307 /**
1308 * Updates the view associated to the activity after the finish of some operation over files
1309 * in the current account.
1310 *
1311 * @param operation Removal operation performed.
1312 * @param result Result of the removal.
1313 */
1314 @Override
1315 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1316 super.onRemoteOperationFinish(operation, result);
1317
1318 if (operation instanceof RemoveFileOperation) {
1319 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1320
1321 } else if (operation instanceof RenameFileOperation) {
1322 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1323
1324 } else if (operation instanceof SynchronizeFileOperation) {
1325 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1326
1327 } else if (operation instanceof CreateFolderOperation) {
1328 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1329
1330 } else if (operation instanceof CreateShareOperation) {
1331 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1332
1333 } else if (operation instanceof UnshareLinkOperation) {
1334 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
1335
1336 } else if (operation instanceof MoveFileOperation) {
1337 onMoveFileOperationFinish((MoveFileOperation)operation, result);
1338 }
1339
1340 }
1341
1342
1343 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
1344 if (result.isSuccess()) {
1345 refreshShowDetails();
1346 refreshListOfFilesFragment();
1347 }
1348 }
1349
1350
1351 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
1352 if (result.isSuccess()) {
1353 refreshShowDetails();
1354 refreshListOfFilesFragment();
1355
1356 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
1357 cleanSecondFragment();
1358 refreshListOfFilesFragment();
1359 }
1360 }
1361
1362 private void refreshShowDetails() {
1363 FileFragment details = getSecondFragment();
1364 if (details != null) {
1365 OCFile file = details.getFile();
1366 if (file != null) {
1367 file = getStorageManager().getFileByPath(file.getRemotePath());
1368 if (details instanceof PreviewMediaFragment) {
1369 // Refresh OCFile of the fragment
1370 ((PreviewMediaFragment) details).updateFile(file);
1371 } else {
1372 showDetails(file);
1373 }
1374 }
1375 invalidateOptionsMenu();
1376 }
1377 }
1378
1379 /**
1380 * Updates the view associated to the activity after the finish of an operation trying to remove a
1381 * file.
1382 *
1383 * @param operation Removal operation performed.
1384 * @param result Result of the removal.
1385 */
1386 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1387 dismissLoadingDialog();
1388
1389 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1390 Toast.LENGTH_LONG);
1391 msg.show();
1392
1393 if (result.isSuccess()) {
1394 OCFile removedFile = operation.getFile();
1395 FileFragment second = getSecondFragment();
1396 if (second != null && removedFile.equals(second.getFile())) {
1397 if (second instanceof PreviewMediaFragment) {
1398 ((PreviewMediaFragment)second).stopPreview(true);
1399 }
1400 setFile(getStorageManager().getFileById(removedFile.getParentId()));
1401 cleanSecondFragment();
1402 }
1403 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1404 refreshListOfFilesFragment();
1405 }
1406 invalidateOptionsMenu();
1407 } else {
1408 if (result.isSslRecoverableException()) {
1409 mLastSslUntrustedServerResult = result;
1410 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1411 }
1412 }
1413 }
1414
1415
1416 /**
1417 * Updates the view associated to the activity after the finish of an operation trying to move a
1418 * file.
1419 *
1420 * @param operation Move operation performed.
1421 * @param result Result of the move operation.
1422 */
1423 private void onMoveFileOperationFinish(MoveFileOperation operation, RemoteOperationResult result) {
1424 if (result.isSuccess()) {
1425 dismissLoadingDialog();
1426 refreshListOfFilesFragment();
1427 } else {
1428 dismissLoadingDialog();
1429 try {
1430 Toast msg = Toast.makeText(FileDisplayActivity.this,
1431 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1432 Toast.LENGTH_LONG);
1433 msg.show();
1434
1435 } catch (NotFoundException e) {
1436 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1437 }
1438 }
1439 }
1440
1441
1442 /**
1443 * Updates the view associated to the activity after the finish of an operation trying to rename a
1444 * file.
1445 *
1446 * @param operation Renaming operation performed.
1447 * @param result Result of the renaming.
1448 */
1449 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1450 dismissLoadingDialog();
1451 OCFile renamedFile = operation.getFile();
1452 if (result.isSuccess()) {
1453 FileFragment details = getSecondFragment();
1454 if (details != null) {
1455 if (details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1456 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1457 showDetails(renamedFile);
1458
1459 } else if (details instanceof PreviewMediaFragment && renamedFile.equals(details.getFile())) {
1460 ((PreviewMediaFragment) details).updateFile(renamedFile);
1461 if (PreviewMediaFragment.canBePreviewed(renamedFile)) {
1462 int position = ((PreviewMediaFragment)details).getPosition();
1463 startMediaPreview(renamedFile, position, true);
1464 } else {
1465 getFileOperationsHelper().openFile(renamedFile);
1466 }
1467 }
1468 }
1469
1470 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1471 refreshListOfFilesFragment();
1472 }
1473
1474 } else {
1475 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1476 Toast.LENGTH_LONG);
1477 msg.show();
1478
1479 if (result.isSslRecoverableException()) {
1480 mLastSslUntrustedServerResult = result;
1481 showUntrustedCertDialog(mLastSslUntrustedServerResult);
1482 }
1483 }
1484 }
1485
1486 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1487 dismissLoadingDialog();
1488 OCFile syncedFile = operation.getLocalFile();
1489 if (!result.isSuccess()) {
1490 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1491 Intent i = new Intent(this, ConflictsResolveActivity.class);
1492 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1493 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1494 startActivity(i);
1495
1496 }
1497
1498 } else {
1499 if (operation.transferWasRequested()) {
1500 onTransferStateChanged(syncedFile, true, true);
1501
1502 } else {
1503 Toast msg = Toast.makeText(this, ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1504 Toast.LENGTH_LONG);
1505 msg.show();
1506 }
1507 }
1508 }
1509
1510 /**
1511 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1512 *
1513 * @param operation Creation operation performed.
1514 * @param result Result of the creation.
1515 */
1516 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1517 if (result.isSuccess()) {
1518 dismissLoadingDialog();
1519 refreshListOfFilesFragment();
1520 } else {
1521 dismissLoadingDialog();
1522 try {
1523 Toast msg = Toast.makeText(FileDisplayActivity.this,
1524 ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
1525 Toast.LENGTH_LONG);
1526 msg.show();
1527
1528 } catch (NotFoundException e) {
1529 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1530 }
1531 }
1532 }
1533
1534
1535 /**
1536 * {@inheritDoc}
1537 */
1538 @Override
1539 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1540 refreshListOfFilesFragment();
1541 FileFragment details = getSecondFragment();
1542 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1543 if (downloading || uploading) {
1544 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1545 } else {
1546 if (!file.fileExists()) {
1547 cleanSecondFragment();
1548 } else {
1549 ((FileDetailFragment)details).updateFileDetails(false, true);
1550 }
1551 }
1552 }
1553
1554 }
1555
1556
1557 private void requestForDownload() {
1558 Account account = getAccount();
1559 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1560 Intent i = new Intent(this, FileDownloader.class);
1561 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1562 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1563 startService(i);
1564 }
1565 }
1566
1567
1568 private OCFile getCurrentDir() {
1569 OCFile file = getFile();
1570 if (file != null) {
1571 if (file.isFolder()) {
1572 return file;
1573 } else if (getStorageManager() != null) {
1574 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
1575 return getStorageManager().getFileByPath(parentPath);
1576 }
1577 }
1578 return null;
1579 }
1580
1581 public void startSyncFolderOperation(OCFile folder) {
1582 long currentSyncTime = System.currentTimeMillis();
1583
1584 mSyncInProgress = true;
1585
1586 // perform folder synchronization
1587 RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
1588 currentSyncTime,
1589 false,
1590 getFileOperationsHelper().isSharedSupported(),
1591 getStorageManager(),
1592 getAccount(),
1593 getApplicationContext()
1594 );
1595 synchFolderOp.execute(getAccount(), this, null, null);
1596
1597 setSupportProgressBarIndeterminateVisibility(true);
1598
1599 setBackgroundText();
1600 }
1601
1602 /**
1603 * Show untrusted cert dialog
1604 */
1605 public void showUntrustedCertDialog(RemoteOperationResult result) {
1606 // Show a dialog with the certificate info
1607 SslUntrustedCertDialog dialog = SslUntrustedCertDialog.newInstanceForFullSslError((CertificateCombinedException)result.getException());
1608 FragmentManager fm = getSupportFragmentManager();
1609 FragmentTransaction ft = fm.beginTransaction();
1610 dialog.show(ft, DIALOG_UNTRUSTED_CERT);
1611 }
1612
1613 private void requestForDownload(OCFile file) {
1614 Account account = getAccount();
1615 if (!mDownloaderBinder.isDownloading(account, file)) {
1616 Intent i = new Intent(this, FileDownloader.class);
1617 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1618 i.putExtra(FileDownloader.EXTRA_FILE, file);
1619 startService(i);
1620 }
1621 }
1622
1623 private void sendDownloadedFile(){
1624 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend);
1625 mWaitingToSend = null;
1626 }
1627
1628
1629 /**
1630 * Requests the download of the received {@link OCFile} , updates the UI
1631 * to monitor the download progress and prepares the activity to send the file
1632 * when the download finishes.
1633 *
1634 * @param file {@link OCFile} to download and preview.
1635 */
1636 public void startDownloadForSending(OCFile file) {
1637 mWaitingToSend = file;
1638 requestForDownload(mWaitingToSend);
1639 boolean hasSecondFragment = (getSecondFragment()!= null);
1640 updateFragmentsVisibility(hasSecondFragment);
1641 }
1642
1643 /**
1644 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1645 *
1646 * @param file Image {@link OCFile} to show.
1647 */
1648 public void startImagePreview(OCFile file) {
1649 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1650 showDetailsIntent.putExtra(EXTRA_FILE, file);
1651 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1652 startActivity(showDetailsIntent);
1653
1654 }
1655
1656 /**
1657 * Stars the preview of an already down media {@link OCFile}.
1658 *
1659 * @param file Media {@link OCFile} to preview.
1660 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1661 * @param autoplay When 'true', the playback will start without user interactions.
1662 */
1663 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1664 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1665 setSecondFragment(mediaFragment);
1666 updateFragmentsVisibility(true);
1667 updateNavigationElementsInActionBar(file);
1668 setFile(file);
1669 }
1670
1671 /**
1672 * Requests the download of the received {@link OCFile} , updates the UI
1673 * to monitor the download progress and prepares the activity to preview
1674 * or open the file when the download finishes.
1675 *
1676 * @param file {@link OCFile} to download and preview.
1677 */
1678 public void startDownloadForPreview(OCFile file) {
1679 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1680 setSecondFragment(detailFragment);
1681 mWaitingToPreview = file;
1682 requestForDownload();
1683 updateFragmentsVisibility(true);
1684 updateNavigationElementsInActionBar(file);
1685 setFile(file);
1686 }
1687
1688
1689 public void cancelTransference(OCFile file) {
1690 getFileOperationsHelper().cancelTransference(file);
1691 if (mWaitingToPreview != null &&
1692 mWaitingToPreview.getRemotePath().equals(file.getRemotePath())) {
1693 mWaitingToPreview = null;
1694 }
1695 if (mWaitingToSend != null &&
1696 mWaitingToSend.getRemotePath().equals(file.getRemotePath())) {
1697 mWaitingToSend = null;
1698 }
1699 onTransferStateChanged(file, false, false);
1700 }
1701
1702 @Override
1703 public void onRefresh() {
1704 OCFileListFragment listOfFiles = getListOfFilesFragment();
1705 if (listOfFiles != null) {
1706 OCFile folder = listOfFiles.getCurrentFile();
1707 if (folder != null) {
1708 /*mFile = mContainerActivity.getStorageManager().getFileById(mFile.getFileId());
1709 listDirectory(mFile);*/
1710 startSyncFolderOperation(folder);
1711 }
1712 }
1713 }
1714
1715 }