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