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