Merge branch 'develop' into feature_previews
[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 as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 *
18 */
19
20 package com.owncloud.android.ui.activity;
21
22 import java.io.File;
23
24 import android.accounts.Account;
25 import android.app.AlertDialog;
26 import android.app.ProgressDialog;
27 import android.app.AlertDialog.Builder;
28 import android.app.Dialog;
29 import android.content.BroadcastReceiver;
30 import android.content.ComponentName;
31 import android.content.ContentResolver;
32 import android.content.Context;
33 import android.content.DialogInterface;
34 import android.content.DialogInterface.OnClickListener;
35 import android.content.Intent;
36 import android.content.IntentFilter;
37 import android.content.ServiceConnection;
38 import android.content.SharedPreferences;
39 import android.content.SharedPreferences.Editor;
40 import android.content.pm.PackageInfo;
41 import android.content.pm.PackageManager.NameNotFoundException;
42 import android.content.res.Resources.NotFoundException;
43 import android.database.Cursor;
44 import android.graphics.Bitmap;
45 import android.graphics.drawable.BitmapDrawable;
46 import android.net.Uri;
47 import android.os.Bundle;
48 import android.os.Handler;
49 import android.os.IBinder;
50 import android.preference.PreferenceManager;
51 import android.provider.MediaStore;
52 import android.support.v4.app.Fragment;
53 import android.support.v4.app.FragmentTransaction;
54 import android.util.Log;
55 import android.view.View;
56 import android.view.ViewGroup;
57 import android.widget.ArrayAdapter;
58 import android.widget.EditText;
59 import android.widget.TextView;
60 import android.widget.Toast;
61
62 import com.actionbarsherlock.app.ActionBar;
63 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
64 import com.actionbarsherlock.app.SherlockFragmentActivity;
65 import com.actionbarsherlock.view.Menu;
66 import com.actionbarsherlock.view.MenuInflater;
67 import com.actionbarsherlock.view.MenuItem;
68 import com.actionbarsherlock.view.Window;
69 import com.owncloud.android.AccountUtils;
70 import com.owncloud.android.authenticator.AccountAuthenticator;
71 import com.owncloud.android.datamodel.DataStorageManager;
72 import com.owncloud.android.datamodel.FileDataStorageManager;
73 import com.owncloud.android.datamodel.OCFile;
74 import com.owncloud.android.files.services.FileDownloader;
75 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
76 import com.owncloud.android.files.services.FileObserverService;
77 import com.owncloud.android.files.services.FileUploader;
78 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
79 import com.owncloud.android.network.OwnCloudClientUtils;
80 import com.owncloud.android.operations.OnRemoteOperationListener;
81 import com.owncloud.android.operations.RemoteOperation;
82 import com.owncloud.android.operations.RemoteOperationResult;
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.RemoteOperationResult.ResultCode;
87 import com.owncloud.android.syncadapter.FileSyncService;
88 import com.owncloud.android.ui.dialog.ChangelogDialog;
89 import com.owncloud.android.ui.dialog.SslValidatorDialog;
90 import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
91 import com.owncloud.android.ui.fragment.FileDetailFragment;
92 import com.owncloud.android.ui.fragment.FileFragment;
93 import com.owncloud.android.ui.fragment.OCFileListFragment;
94 import com.owncloud.android.ui.preview.PreviewImageActivity;
95 import com.owncloud.android.ui.preview.PreviewImageFragment;
96 import com.owncloud.android.ui.preview.PreviewMediaFragment;
97
98 import com.owncloud.android.R;
99 import eu.alefzero.webdav.WebdavClient;
100
101 /**
102 * Displays, what files the user has available in his ownCloud.
103 *
104 * @author Bartek Przybylski
105 * @author David A. Velasco
106 */
107
108 public class FileDisplayActivity extends SherlockFragmentActivity implements
109 OCFileListFragment.ContainerActivity, FileFragment.ContainerActivity, OnNavigationListener, OnSslValidatorListener, OnRemoteOperationListener {
110
111 private ArrayAdapter<String> mDirectories;
112 private OCFile mCurrentDir = null;
113 private OCFile mCurrentFile = null;
114
115 private DataStorageManager mStorageManager;
116 private SyncBroadcastReceiver mSyncBroadcastReceiver;
117 private UploadFinishReceiver mUploadFinishReceiver;
118 private DownloadFinishReceiver mDownloadFinishReceiver;
119 private FileDownloaderBinder mDownloaderBinder = null;
120 private FileUploaderBinder mUploaderBinder = null;
121 private ServiceConnection mDownloadConnection = null, mUploadConnection = null;
122 private RemoteOperationResult mLastSslUntrustedServerResult = null;
123
124 private OCFileListFragment mFileList;
125
126 private boolean mDualPane;
127
128 private static final int DIALOG_SETUP_ACCOUNT = 0;
129 private static final int DIALOG_CREATE_DIR = 1;
130 private static final int DIALOG_ABOUT_APP = 2;
131 public static final int DIALOG_SHORT_WAIT = 3;
132 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 4;
133 private static final int DIALOG_SSL_VALIDATOR = 5;
134 private static final int DIALOG_CERT_NOT_SAVED = 6;
135 private static final String DIALOG_CHANGELOG_TAG = "DIALOG_CHANGELOG";
136
137
138 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
139 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
140
141 private static final String TAG = "FileDisplayActivity";
142
143 private static int[] mMenuIdentifiersToPatch = {R.id.action_about_app};
144
145 private OCFile mWaitingToPreview;
146 private Handler mHandler;
147
148
149 @Override
150 public void onCreate(Bundle savedInstanceState) {
151 Log.d(getClass().toString(), "onCreate() start");
152 super.onCreate(savedInstanceState);
153
154 /// Load of parameters from received intent
155 mCurrentDir = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_FILE); // no check necessary, mCurrenDir == null if the parameter is not in the intent
156 Account account = getIntent().getParcelableExtra(FileDetailFragment.EXTRA_ACCOUNT);
157 if (account != null)
158 AccountUtils.setCurrentOwnCloudAccount(this, account.name);
159
160 /// Load of saved instance state: keep this always before initDataFromCurrentAccount()
161 if(savedInstanceState != null) {
162 // TODO - test if savedInstanceState should take precedence over file in the intent ALWAYS (now), NEVER, or SOME TIMES
163 mCurrentDir = savedInstanceState.getParcelable(FileDetailFragment.EXTRA_FILE);
164 mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDetailActivity.KEY_WAITING_TO_PREVIEW);
165
166 } else {
167 mWaitingToPreview = null;
168 }
169
170 if (!AccountUtils.accountsAreSetup(this)) {
171 /// no account available: FORCE ACCOUNT CREATION
172 mStorageManager = null;
173 createFirstAccount();
174
175 } else { /// at least an account is available
176
177 initDataFromCurrentAccount(); // it checks mCurrentDir and mCurrentFile with the current account
178
179 }
180
181 mUploadConnection = new ListServiceConnection();
182 mDownloadConnection = new ListServiceConnection();
183 bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
184 bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
185
186 // PIN CODE request ; best location is to decide, let's try this first
187 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
188 requestPinCode();
189 }
190
191 // file observer
192 Intent observer_intent = new Intent(this, FileObserverService.class);
193 observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
194 startService(observer_intent);
195
196
197 /// USER INTERFACE
198 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
199
200 // Drop-down navigation
201 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
202 OCFile currFile = mCurrentDir;
203 while(currFile != null && currFile.getFileName() != OCFile.PATH_SEPARATOR) {
204 mDirectories.add(currFile.getFileName());
205 currFile = mStorageManager.getFileById(currFile.getParentId());
206 }
207 mDirectories.add(OCFile.PATH_SEPARATOR);
208
209 // Inflate and set the layout view
210 setContentView(R.layout.files);
211 mFileList = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
212 mDualPane = (findViewById(R.id.file_details_container) != null);
213 if (mDualPane) {
214 initFileDetailsInDualPane();
215 } else {
216 // quick patchES to fix problem in turn from landscape to portrait, when a file is selected in the right pane
217 // TODO serious refactorization in activities and fragments providing file browsing and handling
218 if (mCurrentFile != null) {
219 onFileClick(mCurrentFile);
220 mCurrentFile = null;
221 }
222 Fragment rightPanel = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
223 if (rightPanel != null) {
224 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
225 transaction.remove(rightPanel);
226 transaction.commit();
227 }
228 }
229
230 // Action bar setup
231 ActionBar actionBar = getSupportActionBar();
232 actionBar.setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
233 actionBar.setDisplayHomeAsUpEnabled(mCurrentDir != null && mCurrentDir.getParentId() != 0);
234 actionBar.setDisplayShowTitleEnabled(false);
235 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
236 actionBar.setListNavigationCallbacks(mDirectories, this);
237 setSupportProgressBarIndeterminateVisibility(false); // always AFTER setContentView(...) ; to workaround bug in its implementation
238
239
240 // show changelog, if needed
241 showChangeLog();
242
243 Log.d(getClass().toString(), "onCreate() end");
244 }
245
246
247 /**
248 * Shows a dialog with the change log of the current version after each app update
249 *
250 * TODO make it permanent; by now, only to advice the workaround app for 4.1.x
251 */
252 private void showChangeLog() {
253 if (android.os.Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.JELLY_BEAN) {
254 final String KEY_VERSION = "version";
255 SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
256 int currentVersionNumber = 0;
257 int savedVersionNumber = sharedPref.getInt(KEY_VERSION, 0);
258 try {
259 PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
260 currentVersionNumber = pi.versionCode;
261 } catch (Exception e) {}
262
263 if (currentVersionNumber > savedVersionNumber) {
264 ChangelogDialog.newInstance(true).show(getSupportFragmentManager(), DIALOG_CHANGELOG_TAG);
265 Editor editor = sharedPref.edit();
266 editor.putInt(KEY_VERSION, currentVersionNumber);
267 editor.commit();
268 }
269 }
270 }
271
272
273 /**
274 * Launches the account creation activity. To use when no ownCloud account is available
275 */
276 private void createFirstAccount() {
277 Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
278 intent.putExtra(android.provider.Settings.EXTRA_AUTHORITIES, new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
279 startActivity(intent); // the new activity won't be created until this.onStart() and this.onResume() are finished;
280 }
281
282
283 /**
284 * Load of state dependent of the existence of an ownCloud account
285 */
286 private void initDataFromCurrentAccount() {
287 /// Storage manager initialization - access to local database
288 mStorageManager = new FileDataStorageManager(
289 AccountUtils.getCurrentOwnCloudAccount(this),
290 getContentResolver());
291
292 /// Check if mCurrentDir is a directory
293 if(mCurrentDir != null && !mCurrentDir.isDirectory()) {
294 mCurrentFile = mCurrentDir;
295 mCurrentDir = mStorageManager.getFileById(mCurrentDir.getParentId());
296 }
297
298 /// Check if mCurrentDir and mCurrentFile are in the current account, and update them
299 if (mCurrentDir != null) {
300 mCurrentDir = mStorageManager.getFileByPath(mCurrentDir.getRemotePath()); // mCurrentDir == null if it is not in the current account
301 }
302 if (mCurrentFile != null) {
303 if (mCurrentFile.fileExists()) {
304 mCurrentFile = mStorageManager.getFileByPath(mCurrentFile.getRemotePath()); // mCurrentFile == null if it is not in the current account
305 } // else : keep mCurrentFile with the received value; this is currently the case of an upload in progress, when the user presses the status notification in a landscape tablet
306 }
307
308 /// Default to root if mCurrentDir was not found
309 if (mCurrentDir == null) {
310 mCurrentDir = mStorageManager.getFileByPath("/"); // will be NULL if the database was never synchronized
311 }
312 }
313
314
315 private void initFileDetailsInDualPane() {
316 if (mDualPane && getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG) == null) {
317 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
318 if (mCurrentFile != null) {
319 if (PreviewMediaFragment.canBePreviewed(mCurrentFile)) {
320 if (mCurrentFile.isDown()) {
321 transaction.replace(R.id.file_details_container, new PreviewMediaFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
322 } else {
323 transaction.replace(R.id.file_details_container, new FileDetailFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
324 mWaitingToPreview = mCurrentFile;
325 }
326 } else {
327 transaction.replace(R.id.file_details_container, new FileDetailFragment(mCurrentFile, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
328 }
329 mCurrentFile = null;
330
331 } else {
332 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
333 }
334 transaction.commit();
335 }
336 }
337
338
339 @Override
340 public void onDestroy() {
341 super.onDestroy();
342 if (mDownloadConnection != null)
343 unbindService(mDownloadConnection);
344 if (mUploadConnection != null)
345 unbindService(mUploadConnection);
346 }
347
348
349 @Override
350 public boolean onCreateOptionsMenu(Menu menu) {
351 MenuInflater inflater = getSherlock().getMenuInflater();
352 inflater.inflate(R.menu.main_menu, menu);
353
354 patchHiddenAccents(menu);
355
356 return true;
357 }
358
359 /**
360 * Workaround for this: <a href="http://code.google.com/p/android/issues/detail?id=3974">http://code.google.com/p/android/issues/detail?id=3974</a>
361 *
362 * @param menu Menu to patch
363 */
364 private void patchHiddenAccents(Menu menu) {
365 for (int i = 0; i < mMenuIdentifiersToPatch.length ; i++) {
366 MenuItem aboutItem = menu.findItem(mMenuIdentifiersToPatch[i]);
367 if (aboutItem != null && aboutItem.getIcon() instanceof BitmapDrawable) {
368 // Clip off the bottom three (density independent) pixels of transparent padding
369 Bitmap original = ((BitmapDrawable) aboutItem.getIcon()).getBitmap();
370 float scale = getResources().getDisplayMetrics().density;
371 int clippedHeight = (int) (original.getHeight() - (3 * scale));
372 Bitmap scaled = Bitmap.createBitmap(original, 0, 0, original.getWidth(), clippedHeight);
373 aboutItem.setIcon(new BitmapDrawable(getResources(), scaled));
374 }
375 }
376 }
377
378
379 @Override
380 public boolean onOptionsItemSelected(MenuItem item) {
381 boolean retval = true;
382 switch (item.getItemId()) {
383 case R.id.action_create_dir: {
384 showDialog(DIALOG_CREATE_DIR);
385 break;
386 }
387 case R.id.action_sync_account: {
388 startSynchronization();
389 break;
390 }
391 case R.id.action_upload: {
392 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
393 break;
394 }
395 case R.id.action_settings: {
396 Intent settingsIntent = new Intent(this, Preferences.class);
397 startActivity(settingsIntent);
398 break;
399 }
400 case R.id.action_about_app: {
401 showDialog(DIALOG_ABOUT_APP);
402 break;
403 }
404 case android.R.id.home: {
405 if(mCurrentDir != null && mCurrentDir.getParentId() != 0){
406 onBackPressed();
407 }
408 break;
409 }
410 default:
411 retval = super.onOptionsItemSelected(item);
412 }
413 return retval;
414 }
415
416 private void startSynchronization() {
417 ContentResolver.cancelSync(null, AccountAuthenticator.AUTH_TOKEN_TYPE); // cancel the current synchronizations of any ownCloud account
418 Bundle bundle = new Bundle();
419 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
420 ContentResolver.requestSync(
421 AccountUtils.getCurrentOwnCloudAccount(this),
422 AccountAuthenticator.AUTH_TOKEN_TYPE, bundle);
423 }
424
425
426 @Override
427 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
428 int i = itemPosition;
429 while (i-- != 0) {
430 onBackPressed();
431 }
432 // the next operation triggers a new call to this method, but it's necessary to
433 // ensure that the name exposed in the action bar is the current directory when the
434 // user selected it in the navigation list
435 if (itemPosition != 0)
436 getSupportActionBar().setSelectedNavigationItem(0);
437 return true;
438 }
439
440 /**
441 * Called, when the user selected something for uploading
442 */
443 public void onActivityResult(int requestCode, int resultCode, Intent data) {
444
445 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
446 requestSimpleUpload(data, resultCode);
447
448 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
449 requestMultipleUpload(data, resultCode);
450
451 }
452 }
453
454 private void requestMultipleUpload(Intent data, int resultCode) {
455 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
456 if (filePaths != null) {
457 String[] remotePaths = new String[filePaths.length];
458 String remotePathBase = "";
459 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
460 remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
461 }
462 if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
463 remotePathBase += OCFile.PATH_SEPARATOR;
464 for (int j = 0; j< remotePaths.length; j++) {
465 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
466 }
467
468 Intent i = new Intent(this, FileUploader.class);
469 i.putExtra(FileUploader.KEY_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
470 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
471 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
472 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
473 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
474 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
475 startService(i);
476
477 } else {
478 Log.d("FileDisplay", "User clicked on 'Update' with no selection");
479 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
480 t.show();
481 return;
482 }
483 }
484
485
486 private void requestSimpleUpload(Intent data, int resultCode) {
487 String filepath = null;
488 try {
489 Uri selectedImageUri = data.getData();
490
491 String filemanagerstring = selectedImageUri.getPath();
492 String selectedImagePath = getPath(selectedImageUri);
493
494 if (selectedImagePath != null)
495 filepath = selectedImagePath;
496 else
497 filepath = filemanagerstring;
498
499 } catch (Exception e) {
500 Log.e("FileDisplay", "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
501 e.printStackTrace();
502
503 } finally {
504 if (filepath == null) {
505 Log.e("FileDisplay", "Couldnt resolve path to file");
506 Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
507 t.show();
508 return;
509 }
510 }
511
512 Intent i = new Intent(this, FileUploader.class);
513 i.putExtra(FileUploader.KEY_ACCOUNT,
514 AccountUtils.getCurrentOwnCloudAccount(this));
515 String remotepath = new String();
516 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
517 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
518 }
519 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
520 remotepath += OCFile.PATH_SEPARATOR;
521 remotepath += new File(filepath).getName();
522
523 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
524 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
525 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
526 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
527 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
528 startService(i);
529 }
530
531
532 @Override
533 public void onBackPressed() {
534 if (mDirectories.getCount() <= 1) {
535 finish();
536 return;
537 }
538 popDirname();
539 mFileList.onNavigateUp();
540 mCurrentDir = mFileList.getCurrentFile();
541
542 if (mDualPane) {
543 // Resets the FileDetailsFragment on Tablets so that it always displays
544 Fragment fileFragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
545 if (fileFragment != null && (fileFragment instanceof PreviewMediaFragment || !((FileDetailFragment) fileFragment).isEmpty())) {
546 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
547 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
548 transaction.commit();
549 }
550 }
551
552 if(mCurrentDir.getParentId() == 0){
553 ActionBar actionBar = getSupportActionBar();
554 actionBar.setDisplayHomeAsUpEnabled(false);
555 }
556 }
557
558 @Override
559 protected void onSaveInstanceState(Bundle outState) {
560 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
561 Log.d(getClass().toString(), "onSaveInstanceState() start");
562 super.onSaveInstanceState(outState);
563 outState.putParcelable(FileDetailFragment.EXTRA_FILE, mCurrentDir);
564 if (mDualPane) {
565 FileFragment fragment = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
566 if (fragment != null) {
567 OCFile file = fragment.getFile();
568 if (file != null) {
569 outState.putParcelable(FileDetailFragment.EXTRA_FILE, file);
570 }
571 }
572 }
573 outState.putParcelable(FileDetailActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
574 Log.d(getClass().toString(), "onSaveInstanceState() end");
575 }
576
577 @Override
578 public void onResume() {
579 Log.d(getClass().toString(), "onResume() start");
580 super.onResume();
581
582 if (AccountUtils.accountsAreSetup(this)) {
583
584 if (mStorageManager == null) {
585 // this is necessary for handling the come back to FileDisplayActivity when the first ownCloud account is created
586 initDataFromCurrentAccount();
587 if (mDualPane) {
588 initFileDetailsInDualPane();
589 }
590 }
591
592 // Listen for sync messages
593 IntentFilter syncIntentFilter = new IntentFilter(FileSyncService.SYNC_MESSAGE);
594 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
595 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
596
597 // Listen for upload messages
598 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.UPLOAD_FINISH_MESSAGE);
599 mUploadFinishReceiver = new UploadFinishReceiver();
600 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
601
602 // Listen for download messages
603 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.DOWNLOAD_ADDED_MESSAGE);
604 downloadIntentFilter.addAction(FileDownloader.DOWNLOAD_FINISH_MESSAGE);
605 mDownloadFinishReceiver = new DownloadFinishReceiver();
606 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
607
608 // List current directory
609 mFileList.listDirectory(mCurrentDir); // TODO we should find the way to avoid the need of this (maybe it's not necessary yet; to check)
610
611 } else {
612
613 mStorageManager = null; // an invalid object will be there if all the ownCloud accounts are removed
614 showDialog(DIALOG_SETUP_ACCOUNT);
615
616 }
617 Log.d(getClass().toString(), "onResume() end");
618 }
619
620
621 @Override
622 public void onPause() {
623 Log.d(getClass().toString(), "onPause() start");
624 super.onPause();
625 if (mSyncBroadcastReceiver != null) {
626 unregisterReceiver(mSyncBroadcastReceiver);
627 mSyncBroadcastReceiver = null;
628 }
629 if (mUploadFinishReceiver != null) {
630 unregisterReceiver(mUploadFinishReceiver);
631 mUploadFinishReceiver = null;
632 }
633 if (mDownloadFinishReceiver != null) {
634 unregisterReceiver(mDownloadFinishReceiver);
635 mDownloadFinishReceiver = null;
636 }
637 if (!AccountUtils.accountsAreSetup(this)) {
638 dismissDialog(DIALOG_SETUP_ACCOUNT);
639 }
640
641 Log.d(getClass().toString(), "onPause() end");
642 }
643
644
645 @Override
646 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
647 if (id == DIALOG_SSL_VALIDATOR && mLastSslUntrustedServerResult != null) {
648 ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
649 }
650 }
651
652
653 @Override
654 protected Dialog onCreateDialog(int id) {
655 Dialog dialog = null;
656 AlertDialog.Builder builder;
657 switch (id) {
658 case DIALOG_SETUP_ACCOUNT: {
659 builder = new AlertDialog.Builder(this);
660 builder.setTitle(R.string.main_tit_accsetup);
661 builder.setMessage(R.string.main_wrn_accsetup);
662 builder.setCancelable(false);
663 builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
664 public void onClick(DialogInterface dialog, int which) {
665 createFirstAccount();
666 dialog.dismiss();
667 }
668 });
669 String message = String.format(getString(R.string.common_exit), getString(R.string.app_name));
670 builder.setNegativeButton(message, new OnClickListener() {
671 public void onClick(DialogInterface dialog, int which) {
672 dialog.dismiss();
673 finish();
674 }
675 });
676 //builder.setNegativeButton(android.R.string.cancel, this);
677 dialog = builder.create();
678 break;
679 }
680 case DIALOG_ABOUT_APP: {
681 builder = new AlertDialog.Builder(this);
682 builder.setTitle(getString(R.string.about_title));
683 PackageInfo pkg;
684 try {
685 pkg = getPackageManager().getPackageInfo(getPackageName(), 0);
686 builder.setMessage(String.format(getString(R.string.about_message), getString(R.string.app_name), pkg.versionName));
687 builder.setIcon(android.R.drawable.ic_menu_info_details);
688 dialog = builder.create();
689 } catch (NameNotFoundException e) {
690 builder = null;
691 dialog = null;
692 Log.e(TAG, "Error while showing about dialog", e);
693 }
694 break;
695 }
696 case DIALOG_CREATE_DIR: {
697 builder = new Builder(this);
698 final EditText dirNameInput = new EditText(getBaseContext());
699 builder.setView(dirNameInput);
700 builder.setTitle(R.string.uploader_info_dirname);
701 int typed_color = getResources().getColor(R.color.setup_text_typed);
702 dirNameInput.setTextColor(typed_color);
703 builder.setPositiveButton(android.R.string.ok,
704 new OnClickListener() {
705 public void onClick(DialogInterface dialog, int which) {
706 String directoryName = dirNameInput.getText().toString();
707 if (directoryName.trim().length() == 0) {
708 dialog.cancel();
709 return;
710 }
711
712 // Figure out the path where the dir needs to be created
713 String path;
714 if (mCurrentDir == null) {
715 // this is just a patch; we should ensure that mCurrentDir never is null
716 if (!mStorageManager.fileExists(OCFile.PATH_SEPARATOR)) {
717 OCFile file = new OCFile(OCFile.PATH_SEPARATOR);
718 mStorageManager.saveFile(file);
719 }
720 mCurrentDir = mStorageManager.getFileByPath(OCFile.PATH_SEPARATOR);
721 }
722 path = FileDisplayActivity.this.mCurrentDir.getRemotePath();
723
724 // Create directory
725 path += directoryName + OCFile.PATH_SEPARATOR;
726 Thread thread = new Thread(new DirectoryCreator(path, AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this), new Handler()));
727 thread.start();
728
729 dialog.dismiss();
730
731 showDialog(DIALOG_SHORT_WAIT);
732 }
733 });
734 builder.setNegativeButton(R.string.common_cancel,
735 new OnClickListener() {
736 public void onClick(DialogInterface dialog, int which) {
737 dialog.cancel();
738 }
739 });
740 dialog = builder.create();
741 break;
742 }
743 case DIALOG_SHORT_WAIT: {
744 ProgressDialog working_dialog = new ProgressDialog(this);
745 working_dialog.setMessage(getResources().getString(
746 R.string.wait_a_moment));
747 working_dialog.setIndeterminate(true);
748 working_dialog.setCancelable(false);
749 dialog = working_dialog;
750 break;
751 }
752 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
753 final String[] items = { getString(R.string.actionbar_upload_files),
754 getString(R.string.actionbar_upload_from_apps),
755 getString(R.string.actionbar_failed_instant_upload) };
756 builder = new AlertDialog.Builder(this);
757 builder.setTitle(R.string.actionbar_upload);
758 builder.setItems(items, new DialogInterface.OnClickListener() {
759 public void onClick(DialogInterface dialog, int item) {
760 if (item == 0) {
761 // if (!mDualPane) {
762 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
763 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT,
764 AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this));
765 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
766 // } else {
767 // TODO create and handle new fragment
768 // LocalFileListFragment
769 // }
770 } else if (item == 1) {
771 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
772 action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
773 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
774 ACTION_SELECT_CONTENT_FROM_APPS);
775 } else if (item == 2) {
776 Account account = AccountUtils.getCurrentOwnCloudAccount(FileDisplayActivity.this);
777 Intent action = new Intent(FileDisplayActivity.this, InstantUploadActivity.class);
778 action.putExtra(FileUploader.KEY_ACCOUNT, account);
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 * Translates a content URI of an image to a physical path
813 * on the disk
814 * @param uri The URI to resolve
815 * @return The path to the image or null if it could not be found
816 */
817 public String getPath(Uri uri) {
818 String[] projection = { MediaStore.Images.Media.DATA };
819 Cursor cursor = managedQuery(uri, projection, null, null, null);
820 if (cursor != null) {
821 int column_index = cursor
822 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
823 cursor.moveToFirst();
824 return cursor.getString(column_index);
825 }
826 return null;
827 }
828
829 /**
830 * Pushes a directory to the drop down list
831 * @param directory to push
832 * @throws IllegalArgumentException If the {@link OCFile#isDirectory()} returns false.
833 */
834 public void pushDirname(OCFile directory) {
835 if(!directory.isDirectory()){
836 throw new IllegalArgumentException("Only directories may be pushed!");
837 }
838 mDirectories.insert(directory.getFileName(), 0);
839 mCurrentDir = directory;
840 }
841
842 /**
843 * Pops a directory name from the drop down list
844 * @return True, unless the stack is empty
845 */
846 public boolean popDirname() {
847 mDirectories.remove(mDirectories.getItem(0));
848 return !mDirectories.isEmpty();
849 }
850
851 private class DirectoryCreator implements Runnable {
852 private String mTargetPath;
853 private Account mAccount;
854 private Handler mHandler;
855
856 public DirectoryCreator(String targetPath, Account account, Handler handler) {
857 mTargetPath = targetPath;
858 mAccount = account;
859 mHandler = handler;
860 }
861
862 @Override
863 public void run() {
864 WebdavClient wdc = OwnCloudClientUtils.createOwnCloudClient(mAccount, getApplicationContext());
865 boolean created = wdc.createDirectory(mTargetPath);
866 if (created) {
867 mHandler.post(new Runnable() {
868 @Override
869 public void run() {
870 dismissDialog(DIALOG_SHORT_WAIT);
871
872 // Save new directory in local database
873 OCFile newDir = new OCFile(mTargetPath);
874 newDir.setMimetype("DIR");
875 newDir.setParentId(mCurrentDir.getFileId());
876 mStorageManager.saveFile(newDir);
877
878 // Display the new folder right away
879 mFileList.listDirectory();
880 }
881 });
882
883 } else {
884 mHandler.post(new Runnable() {
885 @Override
886 public void run() {
887 dismissDialog(DIALOG_SHORT_WAIT);
888 try {
889 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
890 msg.show();
891
892 } catch (NotFoundException e) {
893 Log.e(TAG, "Error while trying to show fail message " , e);
894 }
895 }
896 });
897 }
898 }
899
900 }
901
902 // Custom array adapter to override text colors
903 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
904
905 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
906 super(ctx, view);
907 }
908
909 public View getView(int position, View convertView, ViewGroup parent) {
910 View v = super.getView(position, convertView, parent);
911
912 ((TextView) v).setTextColor(getResources().getColorStateList(
913 android.R.color.white));
914 return v;
915 }
916
917 public View getDropDownView(int position, View convertView,
918 ViewGroup parent) {
919 View v = super.getDropDownView(position, convertView, parent);
920
921 ((TextView) v).setTextColor(getResources().getColorStateList(
922 android.R.color.white));
923
924 return v;
925 }
926
927 }
928
929 private class SyncBroadcastReceiver extends BroadcastReceiver {
930
931 /**
932 * {@link BroadcastReceiver} to enable syncing feedback in UI
933 */
934 @Override
935 public void onReceive(Context context, Intent intent) {
936 boolean inProgress = intent.getBooleanExtra(
937 FileSyncService.IN_PROGRESS, false);
938 String accountName = intent
939 .getStringExtra(FileSyncService.ACCOUNT_NAME);
940
941 Log.d("FileDisplay", "sync of account " + accountName
942 + " is in_progress: " + inProgress);
943
944 if (accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name)) {
945
946 String synchFolderRemotePath = intent.getStringExtra(FileSyncService.SYNC_FOLDER_REMOTE_PATH);
947
948 boolean fillBlankRoot = false;
949 if (mCurrentDir == null) {
950 mCurrentDir = mStorageManager.getFileByPath("/");
951 fillBlankRoot = (mCurrentDir != null);
952 }
953
954 if ((synchFolderRemotePath != null && mCurrentDir != null && (mCurrentDir.getRemotePath().equals(synchFolderRemotePath)))
955 || fillBlankRoot ) {
956 if (!fillBlankRoot)
957 mCurrentDir = getStorageManager().getFileByPath(synchFolderRemotePath);
958 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager()
959 .findFragmentById(R.id.fileList);
960 if (fileListFragment != null) {
961 fileListFragment.listDirectory(mCurrentDir);
962 }
963 }
964
965 setSupportProgressBarIndeterminateVisibility(inProgress);
966 removeStickyBroadcast(intent);
967
968 }
969
970 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncService.SYNC_RESULT);
971 if (synchResult != null) {
972 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
973 mLastSslUntrustedServerResult = synchResult;
974 showDialog(DIALOG_SSL_VALIDATOR);
975 }
976 }
977 }
978 }
979
980
981 private class UploadFinishReceiver extends BroadcastReceiver {
982 /**
983 * Once the file upload has finished -> update view
984 * @author David A. Velasco
985 * {@link BroadcastReceiver} to enable upload feedback in UI
986 */
987 @Override
988 public void onReceive(Context context, Intent intent) {
989 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
990 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
991 boolean sameAccount = accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name);
992 boolean isDescendant = (mCurrentDir != null) && (uploadedRemotePath != null) && (uploadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
993 if (sameAccount && isDescendant) {
994 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
995 if (fileListFragment != null) {
996 fileListFragment.listDirectory();
997 }
998 }
999 }
1000
1001 }
1002
1003
1004 /**
1005 * Class waiting for broadcast events from the {@link FielDownloader} service.
1006 *
1007 * Updates the UI when a download is started or finished, provided that it is relevant for the
1008 * current folder.
1009 */
1010 private class DownloadFinishReceiver extends BroadcastReceiver {
1011 @Override
1012 public void onReceive(Context context, Intent intent) {
1013 boolean sameAccount = isSameAccount(context, intent);
1014 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1015 boolean isDescendant = isDescendant(downloadedRemotePath);
1016
1017 if (sameAccount && isDescendant) {
1018 updateLeftPanel();
1019 if (mDualPane) {
1020 updateRightPanel(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1021 }
1022 }
1023
1024 removeStickyBroadcast(intent);
1025 }
1026
1027 private boolean isDescendant(String downloadedRemotePath) {
1028 return (mCurrentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
1029 }
1030
1031 private boolean isSameAccount(Context context, Intent intent) {
1032 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1033 return (accountName != null && accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name));
1034 }
1035 }
1036
1037
1038 protected void updateLeftPanel() {
1039 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1040 if (fileListFragment != null) {
1041 fileListFragment.listDirectory();
1042 }
1043 }
1044
1045 protected void updateRightPanel(String downloadEvent, String downloadedRemotePath, boolean success) {
1046 Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1047 boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
1048 if (fragment != null && fragment instanceof FileDetailFragment) {
1049 FileDetailFragment detailsFragment = (FileDetailFragment) fragment;
1050 OCFile fileInFragment = detailsFragment.getFile();
1051 if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
1052 // the user browsed to other file ; forget the automatic preview
1053 mWaitingToPreview = null;
1054
1055 } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_ADDED_MESSAGE)) {
1056 // grant that the right panel updates the progress bar
1057 detailsFragment.listenForTransferProgress();
1058 detailsFragment.updateFileDetails(true, false);
1059
1060 } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {
1061 // update the right panel
1062 if (success && waitedPreview) {
1063 mWaitingToPreview = mStorageManager.getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
1064 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1065 transaction.replace(R.id.file_details_container, new PreviewMediaFragment(mWaitingToPreview, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1066 transaction.commit();
1067 mWaitingToPreview = null;
1068
1069 } else {
1070 detailsFragment.updateFileDetails(false, (success));
1071 }
1072 }
1073 }
1074 }
1075
1076
1077 /**
1078 * {@inheritDoc}
1079 */
1080 @Override
1081 public DataStorageManager getStorageManager() {
1082 return mStorageManager;
1083 }
1084
1085
1086 /**
1087 * {@inheritDoc}
1088 */
1089 @Override
1090 public void onDirectoryClick(OCFile directory) {
1091 pushDirname(directory);
1092 ActionBar actionBar = getSupportActionBar();
1093 actionBar.setDisplayHomeAsUpEnabled(true);
1094
1095 if (mDualPane) {
1096 // Resets the FileDetailsFragment on Tablets so that it always displays
1097 Fragment fileFragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1098 if (fileFragment != null && (fileFragment instanceof PreviewMediaFragment || !((FileDetailFragment) fileFragment).isEmpty())) {
1099 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1100 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
1101 transaction.commit();
1102 }
1103 }
1104 }
1105
1106
1107 /**
1108 * {@inheritDoc}
1109 */
1110 @Override
1111 public void onFileClick(OCFile file) {
1112 if (file != null && PreviewImageFragment.canBePreviewed(file)) {
1113 // preview image - it handles the download, if needed
1114 startPreviewImage(file);
1115
1116 } else if (file != null && PreviewMediaFragment.canBePreviewed(file)) {
1117 if (file.isDown()) {
1118 // general preview
1119 startMediaPreview(file);
1120
1121 } else {
1122 // automatic download, preview on finish
1123 startDownloadForPreview(file);
1124
1125 }
1126 } else {
1127 // details view
1128 startDetails(file);
1129 }
1130 }
1131
1132 private void startPreviewImage(OCFile file) {
1133 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1134 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1135 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1136 startActivity(showDetailsIntent);
1137 }
1138
1139 private void startMediaPreview(OCFile file) {
1140 if (mDualPane) {
1141 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1142 transaction.replace(R.id.file_details_container, new PreviewMediaFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1143 transaction.commit();
1144
1145 } else {
1146 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1147 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1148 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1149 startActivity(showDetailsIntent);
1150 }
1151 }
1152
1153 private void startDownloadForPreview(OCFile file) {
1154 if (mDualPane) {
1155 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1156 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1157 transaction.commit();
1158 mWaitingToPreview = file;
1159 requestForDownload();
1160
1161 } else {
1162 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1163 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1164 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1165 startActivity(showDetailsIntent);
1166 }
1167 }
1168
1169
1170 private void startDetails(OCFile file) {
1171 if (mDualPane && !file.isImage()) {
1172 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1173 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1174 transaction.commit();
1175 } else {
1176 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1177 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1178 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1179 startActivity(showDetailsIntent);
1180 }
1181 }
1182
1183
1184 /**
1185 * {@inheritDoc}
1186 */
1187 @Override
1188 public OCFile getInitialDirectory() {
1189 return mCurrentDir;
1190 }
1191
1192
1193 /**
1194 * {@inheritDoc}
1195 */
1196 @Override
1197 public void onFileStateChanged() {
1198 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1199 if (fileListFragment != null) {
1200 fileListFragment.listDirectory();
1201 }
1202 }
1203
1204
1205 /**
1206 * {@inheritDoc}
1207 */
1208 @Override
1209 public FileDownloaderBinder getFileDownloaderBinder() {
1210 return mDownloaderBinder;
1211 }
1212
1213
1214 /**
1215 * {@inheritDoc}
1216 */
1217 @Override
1218 public FileUploaderBinder getFileUploaderBinder() {
1219 return mUploaderBinder;
1220 }
1221
1222
1223 /** Defines callbacks for service binding, passed to bindService() */
1224 private class ListServiceConnection implements ServiceConnection {
1225
1226 @Override
1227 public void onServiceConnected(ComponentName component, IBinder service) {
1228 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1229 Log.d(TAG, "Download service connected");
1230 mDownloaderBinder = (FileDownloaderBinder) service;
1231 if (mWaitingToPreview != null) {
1232 requestForDownload();
1233 }
1234
1235 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1236 Log.d(TAG, "Upload service connected");
1237 mUploaderBinder = (FileUploaderBinder) service;
1238 } else {
1239 return;
1240 }
1241 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1242 if (mFileList != null)
1243 mFileList.listDirectory();
1244 if (mDualPane) {
1245 Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1246 if (fragment != null && fragment instanceof FileDetailFragment) {
1247 FileDetailFragment detailFragment = (FileDetailFragment)fragment;
1248 detailFragment.listenForTransferProgress();
1249 detailFragment.updateFileDetails(false, false);
1250 }
1251 }
1252 }
1253
1254 @Override
1255 public void onServiceDisconnected(ComponentName component) {
1256 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1257 Log.d(TAG, "Download service disconnected");
1258 mDownloaderBinder = null;
1259 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1260 Log.d(TAG, "Upload service disconnected");
1261 mUploaderBinder = null;
1262 }
1263 }
1264 };
1265
1266
1267
1268 /**
1269 * Launch an intent to request the PIN code to the user before letting him use the app
1270 */
1271 private void requestPinCode() {
1272 boolean pinStart = false;
1273 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1274 pinStart = appPrefs.getBoolean("set_pincode", false);
1275 if (pinStart) {
1276 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1277 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1278 startActivity(i);
1279 }
1280 }
1281
1282
1283 @Override
1284 public void onSavedCertificate() {
1285 startSynchronization();
1286 }
1287
1288
1289 @Override
1290 public void onFailedSavingCertificate() {
1291 showDialog(DIALOG_CERT_NOT_SAVED);
1292 }
1293
1294
1295 /**
1296 * Updates the view associated to the activity after the finish of some operation over files
1297 * in the current account.
1298 *
1299 * @param operation Removal operation performed.
1300 * @param result Result of the removal.
1301 */
1302 @Override
1303 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1304 if (operation instanceof RemoveFileOperation) {
1305 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1306
1307 } else if (operation instanceof RenameFileOperation) {
1308 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1309
1310 } else if (operation instanceof SynchronizeFileOperation) {
1311 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1312 }
1313 }
1314
1315
1316 /**
1317 * Updates the view associated to the activity after the finish of an operation trying to remove a
1318 * file.
1319 *
1320 * @param operation Removal operation performed.
1321 * @param result Result of the removal.
1322 */
1323 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1324 dismissDialog(DIALOG_SHORT_WAIT);
1325 if (result.isSuccess()) {
1326 Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
1327 msg.show();
1328 OCFile removedFile = operation.getFile();
1329 if (mDualPane) {
1330 FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1331 if (details != null && removedFile.equals(details.getFile())) {
1332 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1333 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
1334 transaction.commit();
1335 }
1336 }
1337 if (mStorageManager.getFileById(removedFile.getParentId()).equals(mCurrentDir)) {
1338 mFileList.listDirectory();
1339 }
1340
1341 } else {
1342 Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
1343 msg.show();
1344 if (result.isSslRecoverableException()) {
1345 mLastSslUntrustedServerResult = result;
1346 showDialog(DIALOG_SSL_VALIDATOR);
1347 }
1348 }
1349 }
1350
1351 /**
1352 * Updates the view associated to the activity after the finish of an operation trying to rename a
1353 * file.
1354 *
1355 * @param operation Renaming operation performed.
1356 * @param result Result of the renaming.
1357 */
1358 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1359 dismissDialog(DIALOG_SHORT_WAIT);
1360 OCFile renamedFile = operation.getFile();
1361 if (result.isSuccess()) {
1362 if (mDualPane) {
1363 FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1364 if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1365 ((FileDetailFragment) details).updateFileDetails(renamedFile, AccountUtils.getCurrentOwnCloudAccount(this));
1366 }
1367 }
1368 if (mStorageManager.getFileById(renamedFile.getParentId()).equals(mCurrentDir)) {
1369 mFileList.listDirectory();
1370 }
1371
1372 } else {
1373 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1374 Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1375 msg.show();
1376 // TODO throw again the new rename dialog
1377 } else {
1378 Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1379 msg.show();
1380 if (result.isSslRecoverableException()) {
1381 mLastSslUntrustedServerResult = result;
1382 showDialog(DIALOG_SSL_VALIDATOR);
1383 }
1384 }
1385 }
1386 }
1387
1388
1389 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1390 dismissDialog(DIALOG_SHORT_WAIT);
1391 OCFile syncedFile = operation.getLocalFile();
1392 if (!result.isSuccess()) {
1393 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1394 Intent i = new Intent(this, ConflictsResolveActivity.class);
1395 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1396 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1397 startActivity(i);
1398
1399 } else {
1400 Toast msg = Toast.makeText(this, R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
1401 msg.show();
1402 }
1403
1404 } else {
1405 if (operation.transferWasRequested()) {
1406 mFileList.listDirectory();
1407 onTransferStateChanged(syncedFile, true, true);
1408
1409 } else {
1410 Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1411 msg.show();
1412 }
1413 }
1414 }
1415
1416
1417 /**
1418 * {@inheritDoc}
1419 */
1420 @Override
1421 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1422 /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1423 if (fileListFragment != null) {
1424 fileListFragment.listDirectory();
1425 }*/
1426 if (mDualPane) {
1427 FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1428 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1429 if (downloading || uploading) {
1430 ((FileDetailFragment)details).updateFileDetails(file, AccountUtils.getCurrentOwnCloudAccount(this));
1431 } else {
1432 ((FileDetailFragment)details).updateFileDetails(false, true);
1433 }
1434 }
1435 }
1436 }
1437
1438
1439 @Override
1440 public void showFragmentWithDetails(OCFile file) {
1441 if (mDualPane) {
1442 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1443 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1444 transaction.commit();
1445
1446 } else {
1447 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1448 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1449 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1450 showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
1451 startActivity(showDetailsIntent);
1452 }
1453 }
1454
1455
1456 private void requestForDownload() {
1457 Account account = AccountUtils.getCurrentOwnCloudAccount(this);
1458 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1459 Intent i = new Intent(this, FileDownloader.class);
1460 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1461 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1462 startService(i);
1463 }
1464 }
1465
1466
1467 }
1468