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