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