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