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