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