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