Fixed automatic playback of media previews after download, in portrait orientation
[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 }
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 public 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 public 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 * Class waiting for broadcast events from the {@link FielDownloader} service.
986 *
987 * Updates the UI when a download is started or finished, provided that it is relevant for the
988 * current folder.
989 */
990 private class DownloadFinishReceiver extends BroadcastReceiver {
991 @Override
992 public void onReceive(Context context, Intent intent) {
993 boolean sameAccount = isSameAccount(context, intent);
994 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
995 boolean isDescendant = isDescendant(downloadedRemotePath);
996
997 if (sameAccount && isDescendant) {
998 updateLeftPanel();
999 if (mDualPane) {
1000 updateRightPanel(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1001 }
1002 }
1003
1004 removeStickyBroadcast(intent);
1005 }
1006
1007 private boolean isDescendant(String downloadedRemotePath) {
1008 return (mCurrentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(mCurrentDir.getRemotePath()));
1009 }
1010
1011 private boolean isSameAccount(Context context, Intent intent) {
1012 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1013 return (accountName != null && accountName.equals(AccountUtils.getCurrentOwnCloudAccount(context).name));
1014 }
1015 }
1016
1017
1018 protected void updateLeftPanel() {
1019 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1020 if (fileListFragment != null) {
1021 fileListFragment.listDirectory();
1022 }
1023 }
1024
1025 protected void updateRightPanel(String downloadEvent, String downloadedRemotePath, boolean success) {
1026 Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1027 boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
1028 if (fragment != null && fragment instanceof FileDetailFragment) {
1029 FileDetailFragment detailsFragment = (FileDetailFragment) fragment;
1030 OCFile fileInFragment = detailsFragment.getFile();
1031 if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
1032 // the user browsed to other file ; forget the automatic preview
1033 mWaitingToPreview = null;
1034
1035 } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_ADDED_MESSAGE)) {
1036 // grant that the right panel updates the progress bar
1037 detailsFragment.listenForTransferProgress();
1038 detailsFragment.updateFileDetails(true, false);
1039
1040 } else if (downloadEvent.equals(FileDownloader.DOWNLOAD_FINISH_MESSAGE)) {
1041 // update the right panel
1042 if (success && waitedPreview) {
1043 mWaitingToPreview = mStorageManager.getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
1044 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1045 transaction.replace(R.id.file_details_container, new PreviewMediaFragment(mWaitingToPreview, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1046 transaction.commit();
1047 mWaitingToPreview = null;
1048
1049 } else {
1050 detailsFragment.updateFileDetails(false, (success));
1051 }
1052 }
1053 }
1054 }
1055
1056
1057 /**
1058 * {@inheritDoc}
1059 */
1060 @Override
1061 public DataStorageManager getStorageManager() {
1062 return mStorageManager;
1063 }
1064
1065
1066 /**
1067 * {@inheritDoc}
1068 */
1069 @Override
1070 public void onDirectoryClick(OCFile directory) {
1071 pushDirname(directory);
1072 ActionBar actionBar = getSupportActionBar();
1073 actionBar.setDisplayHomeAsUpEnabled(true);
1074
1075 if (mDualPane) {
1076 // Resets the FileDetailsFragment on Tablets so that it always displays
1077 Fragment fileFragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1078 if (fileFragment != null && (fileFragment instanceof PreviewMediaFragment || !((FileDetailFragment) fileFragment).isEmpty())) {
1079 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1080 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null), FileDetailFragment.FTAG); // empty FileDetailFragment
1081 transaction.commit();
1082 }
1083 }
1084 }
1085
1086
1087 /**
1088 * {@inheritDoc}
1089 */
1090 @Override
1091 public void onFileClick(OCFile file) {
1092 if (file != null && PreviewImageFragment.canBePreviewed(file)) {
1093 // preview image - it handles the download, if needed
1094 startPreviewImage(file);
1095
1096 } else if (file != null && PreviewMediaFragment.canBePreviewed(file)) {
1097 if (file.isDown()) {
1098 // general preview
1099 startMediaPreview(file);
1100
1101 } else {
1102 // automatic download, preview on finish
1103 startDownloadForPreview(file);
1104
1105 }
1106 } else {
1107 // details view
1108 startDetails(file);
1109 }
1110 }
1111
1112 private void startPreviewImage(OCFile file) {
1113 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1114 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1115 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1116 startActivity(showDetailsIntent);
1117 }
1118
1119 private void startMediaPreview(OCFile file) {
1120 if (mDualPane) {
1121 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1122 transaction.replace(R.id.file_details_container, new PreviewMediaFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1123 transaction.commit();
1124
1125 } else {
1126 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1127 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1128 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1129 startActivity(showDetailsIntent);
1130 }
1131 }
1132
1133 private void startDownloadForPreview(OCFile file) {
1134 if (mDualPane) {
1135 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1136 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1137 transaction.commit();
1138 mWaitingToPreview = file;
1139 requestForDownload();
1140
1141 } else {
1142 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1143 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1144 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1145 startActivity(showDetailsIntent);
1146 }
1147 }
1148
1149
1150 private void startDetails(OCFile file) {
1151 if (mDualPane && !file.isImage()) {
1152 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1153 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1154 transaction.commit();
1155 } else {
1156 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1157 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1158 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1159 startActivity(showDetailsIntent);
1160 }
1161 }
1162
1163
1164 /**
1165 * {@inheritDoc}
1166 */
1167 @Override
1168 public OCFile getInitialDirectory() {
1169 return mCurrentDir;
1170 }
1171
1172
1173 /**
1174 * {@inheritDoc}
1175 */
1176 @Override
1177 public void onFileStateChanged() {
1178 OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1179 if (fileListFragment != null) {
1180 fileListFragment.listDirectory();
1181 }
1182 }
1183
1184
1185 /**
1186 * {@inheritDoc}
1187 */
1188 @Override
1189 public FileDownloaderBinder getFileDownloaderBinder() {
1190 return mDownloaderBinder;
1191 }
1192
1193
1194 /**
1195 * {@inheritDoc}
1196 */
1197 @Override
1198 public FileUploaderBinder getFileUploaderBinder() {
1199 return mUploaderBinder;
1200 }
1201
1202
1203 /** Defines callbacks for service binding, passed to bindService() */
1204 private class ListServiceConnection implements ServiceConnection {
1205
1206 @Override
1207 public void onServiceConnected(ComponentName component, IBinder service) {
1208 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1209 Log.d(TAG, "Download service connected");
1210 mDownloaderBinder = (FileDownloaderBinder) service;
1211 if (mWaitingToPreview != null) {
1212 requestForDownload();
1213 }
1214
1215 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1216 Log.d(TAG, "Upload service connected");
1217 mUploaderBinder = (FileUploaderBinder) service;
1218 } else {
1219 return;
1220 }
1221 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1222 if (mFileList != null)
1223 mFileList.listDirectory();
1224 if (mDualPane) {
1225 Fragment fragment = getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1226 if (fragment != null && fragment instanceof FileDetailFragment) {
1227 FileDetailFragment detailFragment = (FileDetailFragment)fragment;
1228 detailFragment.listenForTransferProgress();
1229 detailFragment.updateFileDetails(false, false);
1230 }
1231 }
1232 }
1233
1234 @Override
1235 public void onServiceDisconnected(ComponentName component) {
1236 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1237 Log.d(TAG, "Download service disconnected");
1238 mDownloaderBinder = null;
1239 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1240 Log.d(TAG, "Upload service disconnected");
1241 mUploaderBinder = null;
1242 }
1243 }
1244 };
1245
1246
1247
1248 /**
1249 * Launch an intent to request the PIN code to the user before letting him use the app
1250 */
1251 private void requestPinCode() {
1252 boolean pinStart = false;
1253 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1254 pinStart = appPrefs.getBoolean("set_pincode", false);
1255 if (pinStart) {
1256 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1257 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1258 startActivity(i);
1259 }
1260 }
1261
1262
1263 @Override
1264 public void onSavedCertificate() {
1265 startSynchronization();
1266 }
1267
1268
1269 @Override
1270 public void onFailedSavingCertificate() {
1271 showDialog(DIALOG_CERT_NOT_SAVED);
1272 }
1273
1274
1275 /**
1276 * Updates the view associated to the activity after the finish of some operation over files
1277 * in the current account.
1278 *
1279 * @param operation Removal operation performed.
1280 * @param result Result of the removal.
1281 */
1282 @Override
1283 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1284 if (operation instanceof RemoveFileOperation) {
1285 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1286
1287 } else if (operation instanceof RenameFileOperation) {
1288 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1289
1290 } else if (operation instanceof SynchronizeFileOperation) {
1291 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1292 }
1293 }
1294
1295
1296 /**
1297 * Updates the view associated to the activity after the finish of an operation trying to remove a
1298 * file.
1299 *
1300 * @param operation Removal operation performed.
1301 * @param result Result of the removal.
1302 */
1303 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1304 dismissDialog(DIALOG_SHORT_WAIT);
1305 if (result.isSuccess()) {
1306 Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
1307 msg.show();
1308 OCFile removedFile = operation.getFile();
1309 if (mDualPane) {
1310 FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1311 if (details != null && removedFile.equals(details.getFile())) {
1312 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1313 transaction.replace(R.id.file_details_container, new FileDetailFragment(null, null)); // empty FileDetailFragment
1314 transaction.commit();
1315 }
1316 }
1317 if (mStorageManager.getFileById(removedFile.getParentId()).equals(mCurrentDir)) {
1318 mFileList.listDirectory();
1319 }
1320
1321 } else {
1322 Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
1323 msg.show();
1324 if (result.isSslRecoverableException()) {
1325 mLastSslUntrustedServerResult = result;
1326 showDialog(DIALOG_SSL_VALIDATOR);
1327 }
1328 }
1329 }
1330
1331 /**
1332 * Updates the view associated to the activity after the finish of an operation trying to rename a
1333 * file.
1334 *
1335 * @param operation Renaming operation performed.
1336 * @param result Result of the renaming.
1337 */
1338 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1339 dismissDialog(DIALOG_SHORT_WAIT);
1340 OCFile renamedFile = operation.getFile();
1341 if (result.isSuccess()) {
1342 if (mDualPane) {
1343 FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1344 if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1345 ((FileDetailFragment) details).updateFileDetails(renamedFile, AccountUtils.getCurrentOwnCloudAccount(this));
1346 }
1347 }
1348 if (mStorageManager.getFileById(renamedFile.getParentId()).equals(mCurrentDir)) {
1349 mFileList.listDirectory();
1350 }
1351
1352 } else {
1353 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1354 Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1355 msg.show();
1356 // TODO throw again the new rename dialog
1357 } else {
1358 Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1359 msg.show();
1360 if (result.isSslRecoverableException()) {
1361 mLastSslUntrustedServerResult = result;
1362 showDialog(DIALOG_SSL_VALIDATOR);
1363 }
1364 }
1365 }
1366 }
1367
1368
1369 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1370 dismissDialog(DIALOG_SHORT_WAIT);
1371 OCFile syncedFile = operation.getLocalFile();
1372 if (!result.isSuccess()) {
1373 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1374 Intent i = new Intent(this, ConflictsResolveActivity.class);
1375 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1376 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1377 startActivity(i);
1378
1379 } else {
1380 Toast msg = Toast.makeText(this, R.string.sync_file_fail_msg, Toast.LENGTH_LONG);
1381 msg.show();
1382 }
1383
1384 } else {
1385 if (operation.transferWasRequested()) {
1386 mFileList.listDirectory();
1387 onTransferStateChanged(syncedFile, true, true);
1388
1389 } else {
1390 Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1391 msg.show();
1392 }
1393 }
1394 }
1395
1396
1397 /**
1398 * {@inheritDoc}
1399 */
1400 @Override
1401 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1402 /*OCFileListFragment fileListFragment = (OCFileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
1403 if (fileListFragment != null) {
1404 fileListFragment.listDirectory();
1405 }*/
1406 if (mDualPane) {
1407 FileFragment details = (FileFragment) getSupportFragmentManager().findFragmentByTag(FileDetailFragment.FTAG);
1408 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1409 if (downloading || uploading) {
1410 ((FileDetailFragment)details).updateFileDetails(file, AccountUtils.getCurrentOwnCloudAccount(this));
1411 } else {
1412 ((FileDetailFragment)details).updateFileDetails(false, true);
1413 }
1414 }
1415 }
1416 }
1417
1418
1419 @Override
1420 public void showFragmentWithDetails(OCFile file) {
1421 if (mDualPane) {
1422 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
1423 transaction.replace(R.id.file_details_container, new FileDetailFragment(file, AccountUtils.getCurrentOwnCloudAccount(this)), FileDetailFragment.FTAG);
1424 transaction.commit();
1425
1426 } else {
1427 Intent showDetailsIntent = new Intent(this, FileDetailActivity.class);
1428 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_FILE, file);
1429 showDetailsIntent.putExtra(FileDetailFragment.EXTRA_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
1430 showDetailsIntent.putExtra(FileDetailActivity.EXTRA_MODE, FileDetailActivity.MODE_DETAILS);
1431 startActivity(showDetailsIntent);
1432 }
1433 }
1434
1435
1436 private void requestForDownload() {
1437 Account account = AccountUtils.getCurrentOwnCloudAccount(this);
1438 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1439 Intent i = new Intent(this, FileDownloader.class);
1440 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1441 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1442 startService(i);
1443 }
1444 }
1445
1446
1447 }