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