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