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