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