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