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