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