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