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