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