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