OC-2967: Grant that files are downloaded automatically when the action is triggered...
[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.Dialog;
26 import android.app.ProgressDialog;
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.SyncRequest;
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.IBinder;
42 import android.preference.PreferenceManager;
43 import android.provider.MediaStore;
44 import android.support.v4.app.Fragment;
45 import android.support.v4.app.FragmentTransaction;
46 //import android.support.v4.content.LocalBroadcastManager;
47 import android.util.Log;
48 import android.view.View;
49 import android.view.ViewGroup;
50 import android.widget.ArrayAdapter;
51 import android.widget.TextView;
52 import android.widget.Toast;
53
54 import com.actionbarsherlock.app.ActionBar;
55 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
56 import com.actionbarsherlock.view.Menu;
57 import com.actionbarsherlock.view.MenuInflater;
58 import com.actionbarsherlock.view.MenuItem;
59 import com.actionbarsherlock.view.Window;
60 import com.owncloud.android.MainApp;
61 import com.owncloud.android.R;
62 import com.owncloud.android.datamodel.OCFile;
63 import com.owncloud.android.files.services.FileDownloader;
64 import com.owncloud.android.files.services.FileObserverService;
65 import com.owncloud.android.files.services.FileUploader;
66 import com.owncloud.android.files.services.FileDownloader.FileDownloaderBinder;
67 import com.owncloud.android.files.services.FileUploader.FileUploaderBinder;
68 import com.owncloud.android.operations.CreateFolderOperation;
69
70 import com.owncloud.android.lib.operations.common.RemoteOperation;
71 import com.owncloud.android.lib.operations.common.RemoteOperationResult;
72 import com.owncloud.android.lib.operations.common.RemoteOperationResult.ResultCode;
73 import com.owncloud.android.operations.CreateShareOperation;
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.SynchronizeFolderOperation;
78 import com.owncloud.android.operations.UnshareLinkOperation;
79 import com.owncloud.android.services.OperationsService;
80 import com.owncloud.android.syncadapter.FileSyncAdapter;
81 import com.owncloud.android.ui.dialog.EditNameDialog;
82 import com.owncloud.android.ui.dialog.EditNameDialog.EditNameDialogListener;
83 import com.owncloud.android.ui.dialog.SslValidatorDialog;
84 import com.owncloud.android.ui.dialog.SslValidatorDialog.OnSslValidatorListener;
85 import com.owncloud.android.ui.fragment.FileDetailFragment;
86 import com.owncloud.android.ui.fragment.FileFragment;
87 import com.owncloud.android.ui.fragment.OCFileListFragment;
88 import com.owncloud.android.ui.preview.PreviewImageActivity;
89 import com.owncloud.android.ui.preview.PreviewMediaFragment;
90 import com.owncloud.android.ui.preview.PreviewVideoActivity;
91 import com.owncloud.android.utils.DisplayUtils;
92 import com.owncloud.android.utils.Log_OC;
93
94
95 /**
96 * Displays, what files the user has available in his ownCloud.
97 *
98 * @author Bartek Przybylski
99 * @author David A. Velasco
100 */
101
102 public class FileDisplayActivity extends HookActivity implements
103 OCFileListFragment.ContainerActivity, FileDetailFragment.ContainerActivity, OnNavigationListener, OnSslValidatorListener, EditNameDialogListener {
104
105 private ArrayAdapter<String> mDirectories;
106
107 private SyncBroadcastReceiver mSyncBroadcastReceiver;
108 private UploadFinishReceiver mUploadFinishReceiver;
109 private DownloadFinishReceiver mDownloadFinishReceiver;
110 //private OperationsServiceReceiver mOperationsServiceReceiver;
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 boolean mDualPane;
117 private View mLeftFragmentContainer;
118 private View mRightFragmentContainer;
119
120 private static final String KEY_WAITING_TO_PREVIEW = "WAITING_TO_PREVIEW";
121 private static final String KEY_SYNC_IN_PROGRESS = "SYNC_IN_PROGRESS";
122 private static final String KEY_REFRESH_SHARES_IN_PROGRESS = "SHARES_IN_PROGRESS";
123
124 public static final int DIALOG_SHORT_WAIT = 0;
125 private static final int DIALOG_CHOOSE_UPLOAD_SOURCE = 1;
126 private static final int DIALOG_SSL_VALIDATOR = 2;
127 private static final int DIALOG_CERT_NOT_SAVED = 3;
128
129 public static final String ACTION_DETAILS = "com.owncloud.android.ui.activity.action.DETAILS";
130
131 private static final int ACTION_SELECT_CONTENT_FROM_APPS = 1;
132 private static final int ACTION_SELECT_MULTIPLE_FILES = 2;
133
134 private static final String TAG = FileDisplayActivity.class.getSimpleName();
135
136 private static final String TAG_LIST_OF_FILES = "LIST_OF_FILES";
137 private static final String TAG_SECOND_FRAGMENT = "SECOND_FRAGMENT";
138
139 private OCFile mWaitingToPreview;
140
141 private boolean mSyncInProgress = false;
142 //private boolean mRefreshSharesInProgress = false;
143
144 private OCFile mWaitingToSend;
145
146 @Override
147 protected void onCreate(Bundle savedInstanceState) {
148 Log_OC.d(TAG, "onCreate() start");
149 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
150
151 super.onCreate(savedInstanceState); // this calls onAccountChanged() when ownCloud Account is valid
152
153 /// bindings to transference services
154 mUploadConnection = new ListServiceConnection();
155 mDownloadConnection = new ListServiceConnection();
156 bindService(new Intent(this, FileUploader.class), mUploadConnection, Context.BIND_AUTO_CREATE);
157 bindService(new Intent(this, FileDownloader.class), mDownloadConnection, Context.BIND_AUTO_CREATE);
158
159 // PIN CODE request ; best location is to decide, let's try this first
160 if (getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_MAIN) && savedInstanceState == null) {
161 requestPinCode();
162 } else if (getIntent().getAction() == null && savedInstanceState == null) {
163 requestPinCode();
164 }
165
166 /// file observer
167 Intent observer_intent = new Intent(this, FileObserverService.class);
168 observer_intent.putExtra(FileObserverService.KEY_FILE_CMD, FileObserverService.CMD_INIT_OBSERVED_LIST);
169 startService(observer_intent);
170
171 /// Load of saved instance state
172 if(savedInstanceState != null) {
173 mWaitingToPreview = (OCFile) savedInstanceState.getParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW);
174 mSyncInProgress = savedInstanceState.getBoolean(KEY_SYNC_IN_PROGRESS);
175 //mRefreshSharesInProgress = savedInstanceState.getBoolean(KEY_REFRESH_SHARES_IN_PROGRESS);
176
177 } else {
178 mWaitingToPreview = null;
179 mSyncInProgress = false;
180 //mRefreshSharesInProgress = false;
181 }
182
183 /// USER INTERFACE
184
185 // Inflate and set the layout view
186 setContentView(R.layout.files);
187 mDualPane = getResources().getBoolean(R.bool.large_land_layout);
188 mLeftFragmentContainer = findViewById(R.id.left_fragment_container);
189 mRightFragmentContainer = findViewById(R.id.right_fragment_container);
190 if (savedInstanceState == null) {
191 createMinFragments();
192 } else {
193 Log_OC.d(TAG, "Init the secondFragment again");
194 if (mDualPane) {
195 initFragmentsWithFile();
196 }
197 }
198
199 // Action bar setup
200 mDirectories = new CustomArrayAdapter<String>(this, R.layout.sherlock_spinner_dropdown_item);
201 getSupportActionBar().setHomeButtonEnabled(true); // mandatory since Android ICS, according to the official documentation
202 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/); // always AFTER setContentView(...) ; to work around bug in its implementation
203
204 Log_OC.d(TAG, "onCreate() end");
205 }
206
207 @Override
208 protected void onStart() {
209 super.onStart();
210 getSupportActionBar().setIcon(DisplayUtils.getSeasonalIconId());
211 refeshListOfFilesFragment();
212 }
213
214 @Override
215 protected void onDestroy() {
216 super.onDestroy();
217 if (mDownloadConnection != null)
218 unbindService(mDownloadConnection);
219 if (mUploadConnection != null)
220 unbindService(mUploadConnection);
221 }
222
223
224 /**
225 * Called when the ownCloud {@link Account} associated to the Activity was just updated.
226 */
227 @Override
228 protected void onAccountSet(boolean stateWasRecovered) {
229 super.onAccountSet(stateWasRecovered);
230 if (getAccount() != null) {
231 /// Check whether the 'main' OCFile handled by the Activity is contained in the current Account
232 OCFile file = getFile();
233 // get parent from path
234 String parentPath = "";
235 if (file != null) {
236 if (file.isDown() && file.getLastSyncDateForProperties() == 0) {
237 // upload in progress - right now, files are not inserted in the local cache until the upload is successful
238 // get parent from path
239 parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
240 if (getStorageManager().getFileByPath(parentPath) == null)
241 file = null; // not able to know the directory where the file is uploading
242 } else {
243 file = getStorageManager().getFileByPath(file.getRemotePath()); // currentDir = null if not in the current Account
244 }
245 }
246 if (file == null) {
247 // fall back to root folder
248 file = getStorageManager().getFileByPath(OCFile.ROOT_PATH); // never returns null
249 }
250 setFile(file);
251 setNavigationListWithFolder(file);
252
253 if (!stateWasRecovered) {
254 Log_OC.e(TAG, "Initializing Fragments in onAccountChanged..");
255 initFragmentsWithFile();
256 if (file.isFolder()) {
257 startSyncFolderOperation(file);
258 }
259
260 } else {
261 updateFragmentsVisibility(!file.isFolder());
262 updateNavigationElementsInActionBar(file.isFolder() ? null : file);
263 }
264 }
265 }
266
267
268 private void setNavigationListWithFolder(OCFile file) {
269 mDirectories.clear();
270 OCFile fileIt = file;
271 String parentPath;
272 while(fileIt != null && fileIt.getFileName() != OCFile.ROOT_PATH) {
273 if (fileIt.isFolder()) {
274 mDirectories.add(fileIt.getFileName());
275 }
276 // get parent from path
277 parentPath = fileIt.getRemotePath().substring(0, fileIt.getRemotePath().lastIndexOf(fileIt.getFileName()));
278 fileIt = getStorageManager().getFileByPath(parentPath);
279 }
280 mDirectories.add(OCFile.PATH_SEPARATOR);
281 }
282
283
284 private void createMinFragments() {
285 OCFileListFragment listOfFiles = new OCFileListFragment();
286 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
287 transaction.add(R.id.left_fragment_container, listOfFiles, TAG_LIST_OF_FILES);
288 transaction.commit();
289 }
290
291 private void initFragmentsWithFile() {
292 if (getAccount() != null && getFile() != null) {
293 /// First fragment
294 OCFileListFragment listOfFiles = getListOfFilesFragment();
295 if (listOfFiles != null) {
296 listOfFiles.listDirectory(getCurrentDir());
297 } else {
298 Log.e(TAG, "Still have a chance to lose the initializacion of list fragment >(");
299 }
300
301 /// Second fragment
302 OCFile file = getFile();
303 Fragment secondFragment = chooseInitialSecondFragment(file);
304 if (secondFragment != null) {
305 setSecondFragment(secondFragment);
306 updateFragmentsVisibility(true);
307 updateNavigationElementsInActionBar(file);
308
309 } else {
310 cleanSecondFragment();
311 }
312
313 } else {
314 Log.wtf(TAG, "initFragments() called with invalid NULLs!");
315 if (getAccount() == null) {
316 Log.wtf(TAG, "\t account is NULL");
317 }
318 if (getFile() == null) {
319 Log.wtf(TAG, "\t file is NULL");
320 }
321 }
322 }
323
324 private Fragment chooseInitialSecondFragment(OCFile file) {
325 Fragment secondFragment = null;
326 if (file != null && !file.isFolder()) {
327 if (file.isDown() && PreviewMediaFragment.canBePreviewed(file)
328 && file.getLastSyncDateForProperties() > 0 // temporal fix
329 ) {
330 int startPlaybackPosition = getIntent().getIntExtra(PreviewVideoActivity.EXTRA_START_POSITION, 0);
331 boolean autoplay = getIntent().getBooleanExtra(PreviewVideoActivity.EXTRA_AUTOPLAY, true);
332 secondFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
333
334 } else {
335 secondFragment = new FileDetailFragment(file, getAccount());
336 }
337 }
338 return secondFragment;
339 }
340
341
342 /**
343 * Replaces the second fragment managed by the activity with the received as
344 * a parameter.
345 *
346 * Assumes never will be more than two fragments managed at the same time.
347 *
348 * @param fragment New second Fragment to set.
349 */
350 private void setSecondFragment(Fragment fragment) {
351 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
352 transaction.replace(R.id.right_fragment_container, fragment, TAG_SECOND_FRAGMENT);
353 transaction.commit();
354 }
355
356
357 private void updateFragmentsVisibility(boolean existsSecondFragment) {
358 if (mDualPane) {
359 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
360 mLeftFragmentContainer.setVisibility(View.VISIBLE);
361 }
362 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
363 mRightFragmentContainer.setVisibility(View.VISIBLE);
364 }
365
366 } else if (existsSecondFragment) {
367 if (mLeftFragmentContainer.getVisibility() != View.GONE) {
368 mLeftFragmentContainer.setVisibility(View.GONE);
369 }
370 if (mRightFragmentContainer.getVisibility() != View.VISIBLE) {
371 mRightFragmentContainer.setVisibility(View.VISIBLE);
372 }
373
374 } else {
375 if (mLeftFragmentContainer.getVisibility() != View.VISIBLE) {
376 mLeftFragmentContainer.setVisibility(View.VISIBLE);
377 }
378 if (mRightFragmentContainer.getVisibility() != View.GONE) {
379 mRightFragmentContainer.setVisibility(View.GONE);
380 }
381 }
382 }
383
384
385 private OCFileListFragment getListOfFilesFragment() {
386 Fragment listOfFiles = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_LIST_OF_FILES);
387 if (listOfFiles != null) {
388 return (OCFileListFragment)listOfFiles;
389 }
390 Log_OC.wtf(TAG, "Access to unexisting list of files fragment!!");
391 return null;
392 }
393
394 protected FileFragment getSecondFragment() {
395 Fragment second = getSupportFragmentManager().findFragmentByTag(FileDisplayActivity.TAG_SECOND_FRAGMENT);
396 if (second != null) {
397 return (FileFragment)second;
398 }
399 return null;
400 }
401
402 public void cleanSecondFragment() {
403 Fragment second = getSecondFragment();
404 if (second != null) {
405 FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
406 tr.remove(second);
407 tr.commit();
408 }
409 updateFragmentsVisibility(false);
410 updateNavigationElementsInActionBar(null);
411 }
412
413 protected void refeshListOfFilesFragment() {
414 OCFileListFragment fileListFragment = getListOfFilesFragment();
415 if (fileListFragment != null) {
416 fileListFragment.listDirectory();
417 }
418 }
419
420 protected void refreshSecondFragment(String downloadEvent, String downloadedRemotePath, boolean success) {
421 FileFragment secondFragment = getSecondFragment();
422 boolean waitedPreview = (mWaitingToPreview != null && mWaitingToPreview.getRemotePath().equals(downloadedRemotePath));
423 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
424 FileDetailFragment detailsFragment = (FileDetailFragment) secondFragment;
425 OCFile fileInFragment = detailsFragment.getFile();
426 if (fileInFragment != null && !downloadedRemotePath.equals(fileInFragment.getRemotePath())) {
427 // the user browsed to other file ; forget the automatic preview
428 mWaitingToPreview = null;
429
430 } else if (downloadEvent.equals(FileDownloader.getDownloadAddedMessage())) {
431 // grant that the right panel updates the progress bar
432 detailsFragment.listenForTransferProgress();
433 detailsFragment.updateFileDetails(true, false);
434
435 } else if (downloadEvent.equals(FileDownloader.getDownloadFinishMessage())) {
436 // update the right panel
437 boolean detailsFragmentChanged = false;
438 if (waitedPreview) {
439 if (success) {
440 mWaitingToPreview = getStorageManager().getFileById(mWaitingToPreview.getFileId()); // update the file from database, for the local storage path
441 if (PreviewMediaFragment.canBePreviewed(mWaitingToPreview)) {
442 startMediaPreview(mWaitingToPreview, 0, true);
443 detailsFragmentChanged = true;
444 } else {
445 getFileOperationsHelper().openFile(mWaitingToPreview, this);
446 }
447 }
448 mWaitingToPreview = null;
449 }
450 if (!detailsFragmentChanged) {
451 detailsFragment.updateFileDetails(false, (success));
452 }
453 }
454 }
455 }
456
457 @Override
458 public boolean onCreateOptionsMenu(Menu menu) {
459 MenuInflater inflater = getSherlock().getMenuInflater();
460 inflater.inflate(R.menu.main_menu, menu);
461 return true;
462 }
463
464 @Override
465 public boolean onOptionsItemSelected(MenuItem item) {
466 boolean retval = true;
467 switch (item.getItemId()) {
468 case R.id.action_create_dir: {
469 EditNameDialog dialog = EditNameDialog.newInstance(getString(R.string.uploader_info_dirname), "", -1, -1, this);
470 dialog.show(getSupportFragmentManager(), "createdirdialog");
471 break;
472 }
473 case R.id.action_sync_account: {
474 startSynchronization();
475 break;
476 }
477 case R.id.action_upload: {
478 showDialog(DIALOG_CHOOSE_UPLOAD_SOURCE);
479 break;
480 }
481 case R.id.action_settings: {
482 Intent settingsIntent = new Intent(this, Preferences.class);
483 startActivity(settingsIntent);
484 break;
485 }
486 case android.R.id.home: {
487 FileFragment second = getSecondFragment();
488 OCFile currentDir = getCurrentDir();
489 if((currentDir != null && currentDir.getParentId() != 0) ||
490 (second != null && second.getFile() != null)) {
491 onBackPressed();
492
493 }
494 break;
495 }
496 default:
497 retval = super.onOptionsItemSelected(item);
498 }
499 return retval;
500 }
501
502 private void startSynchronization() {
503 Log_OC.e(TAG, "Got to start sync");
504 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.KITKAT) {
505 Log_OC.e(TAG, "Canceling all syncs for " + MainApp.getAuthority());
506 ContentResolver.cancelSync(null, MainApp.getAuthority()); // cancel the current synchronizations of any ownCloud account
507 Bundle bundle = new Bundle();
508 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
509 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
510 Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority());
511 ContentResolver.requestSync(
512 getAccount(),
513 MainApp.getAuthority(), bundle);
514 } else {
515 Log_OC.e(TAG, "Requesting sync for " + getAccount().name + " at " + MainApp.getAuthority() + " with new API");
516 SyncRequest.Builder builder = new SyncRequest.Builder();
517 builder.setSyncAdapter(getAccount(), MainApp.getAuthority());
518 builder.setExpedited(true);
519 builder.setManual(true);
520 builder.syncOnce();
521 SyncRequest request = builder.build();
522 ContentResolver.requestSync(request);
523 }
524 }
525
526
527 @Override
528 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
529 if (itemPosition != 0) {
530 String targetPath = "";
531 for (int i=itemPosition; i < mDirectories.getCount() - 1; i++) {
532 targetPath = mDirectories.getItem(i) + OCFile.PATH_SEPARATOR + targetPath;
533 }
534 targetPath = OCFile.PATH_SEPARATOR + targetPath;
535 OCFile targetFolder = getStorageManager().getFileByPath(targetPath);
536 if (targetFolder != null) {
537 browseTo(targetFolder);
538 }
539
540 // the next operation triggers a new call to this method, but it's necessary to
541 // ensure that the name exposed in the action bar is the current directory when the
542 // user selected it in the navigation list
543 if (getSupportActionBar().getNavigationMode() == ActionBar.NAVIGATION_MODE_LIST && itemPosition != 0)
544 getSupportActionBar().setSelectedNavigationItem(0);
545 }
546 return true;
547 }
548
549 /**
550 * Called, when the user selected something for uploading
551 */
552 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
553 super.onActivityResult(requestCode, resultCode, data);
554
555 if (requestCode == ACTION_SELECT_CONTENT_FROM_APPS && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
556 requestSimpleUpload(data, resultCode);
557
558 } else if (requestCode == ACTION_SELECT_MULTIPLE_FILES && (resultCode == RESULT_OK || resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)) {
559 requestMultipleUpload(data, resultCode);
560
561 }
562 }
563
564 private void requestMultipleUpload(Intent data, int resultCode) {
565 String[] filePaths = data.getStringArrayExtra(UploadFilesActivity.EXTRA_CHOSEN_FILES);
566 if (filePaths != null) {
567 String[] remotePaths = new String[filePaths.length];
568 String remotePathBase = "";
569 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
570 remotePathBase += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
571 }
572 if (!remotePathBase.endsWith(OCFile.PATH_SEPARATOR))
573 remotePathBase += OCFile.PATH_SEPARATOR;
574 for (int j = 0; j< remotePaths.length; j++) {
575 remotePaths[j] = remotePathBase + (new File(filePaths[j])).getName();
576 }
577
578 Intent i = new Intent(this, FileUploader.class);
579 i.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
580 i.putExtra(FileUploader.KEY_LOCAL_FILE, filePaths);
581 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotePaths);
582 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
583 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
584 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
585 startService(i);
586
587 } else {
588 Log_OC.d(TAG, "User clicked on 'Update' with no selection");
589 Toast t = Toast.makeText(this, getString(R.string.filedisplay_no_file_selected), Toast.LENGTH_LONG);
590 t.show();
591 return;
592 }
593 }
594
595
596 private void requestSimpleUpload(Intent data, int resultCode) {
597 String filepath = null;
598 try {
599 Uri selectedImageUri = data.getData();
600
601 String filemanagerstring = selectedImageUri.getPath();
602 String selectedImagePath = getPath(selectedImageUri);
603
604 if (selectedImagePath != null)
605 filepath = selectedImagePath;
606 else
607 filepath = filemanagerstring;
608
609 } catch (Exception e) {
610 Log_OC.e(TAG, "Unexpected exception when trying to read the result of Intent.ACTION_GET_CONTENT", e);
611 e.printStackTrace();
612
613 } finally {
614 if (filepath == null) {
615 Log_OC.e(TAG, "Couldnt resolve path to file");
616 Toast t = Toast.makeText(this, getString(R.string.filedisplay_unexpected_bad_get_content), Toast.LENGTH_LONG);
617 t.show();
618 return;
619 }
620 }
621
622 Intent i = new Intent(this, FileUploader.class);
623 i.putExtra(FileUploader.KEY_ACCOUNT,
624 getAccount());
625 String remotepath = new String();
626 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
627 remotepath += OCFile.PATH_SEPARATOR + mDirectories.getItem(j);
628 }
629 if (!remotepath.endsWith(OCFile.PATH_SEPARATOR))
630 remotepath += OCFile.PATH_SEPARATOR;
631 remotepath += new File(filepath).getName();
632
633 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
634 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
635 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
636 if (resultCode == UploadFilesActivity.RESULT_OK_AND_MOVE)
637 i.putExtra(FileUploader.KEY_LOCAL_BEHAVIOUR, FileUploader.LOCAL_BEHAVIOUR_MOVE);
638 startService(i);
639 }
640
641 @Override
642 public void onBackPressed() {
643 OCFileListFragment listOfFiles = getListOfFilesFragment();
644 if (mDualPane || getSecondFragment() == null) {
645 if (listOfFiles != null) { // should never be null, indeed
646 if (mDirectories.getCount() <= 1) {
647 finish();
648 return;
649 }
650 int levelsUp = listOfFiles.onBrowseUp();
651 for (int i=0; i < levelsUp && mDirectories.getCount() > 1 ; i++) {
652 popDirname();
653 }
654 }
655 }
656 if (listOfFiles != null) { // should never be null, indeed
657 setFile(listOfFiles.getCurrentFile());
658 }
659 cleanSecondFragment();
660
661 }
662
663 @Override
664 protected void onSaveInstanceState(Bundle outState) {
665 // responsibility of restore is preferred in onCreate() before than in onRestoreInstanceState when there are Fragments involved
666 Log_OC.e(TAG, "onSaveInstanceState() start");
667 super.onSaveInstanceState(outState);
668 outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);
669 outState.putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress);
670 //outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS, mRefreshSharesInProgress);
671
672 Log_OC.d(TAG, "onSaveInstanceState() end");
673 }
674
675
676
677 @Override
678 protected void onResume() {
679 super.onResume();
680 Log_OC.e(TAG, "onResume() start");
681
682 // Listen for sync messages
683 IntentFilter syncIntentFilter = new IntentFilter(FileSyncAdapter.EVENT_FULL_SYNC_START);
684 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_END);
685 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_SIZE_SYNCED);
686 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
687 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
688 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
689 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
690 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
691 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
692
693 // Listen for upload messages
694 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
695 mUploadFinishReceiver = new UploadFinishReceiver();
696 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
697
698 // Listen for download messages
699 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
700 downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
701 mDownloadFinishReceiver = new DownloadFinishReceiver();
702 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
703
704 // Listen for messages from the OperationsService
705 /*
706 IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
707 operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
708 mOperationsServiceReceiver = new OperationsServiceReceiver();
709 LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
710 */
711
712 Log_OC.d(TAG, "onResume() end");
713 }
714
715
716 @Override
717 protected void onPause() {
718 super.onPause();
719 Log_OC.e(TAG, "onPause() start");
720 if (mSyncBroadcastReceiver != null) {
721 unregisterReceiver(mSyncBroadcastReceiver);
722 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
723 mSyncBroadcastReceiver = null;
724 }
725 if (mUploadFinishReceiver != null) {
726 unregisterReceiver(mUploadFinishReceiver);
727 mUploadFinishReceiver = null;
728 }
729 if (mDownloadFinishReceiver != null) {
730 unregisterReceiver(mDownloadFinishReceiver);
731 mDownloadFinishReceiver = null;
732 }
733 /*
734 if (mOperationsServiceReceiver != null) {
735 LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
736 mOperationsServiceReceiver = null;
737 }
738 */
739 Log_OC.d(TAG, "onPause() end");
740 }
741
742
743 @Override
744 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
745 if (id == DIALOG_SSL_VALIDATOR && mLastSslUntrustedServerResult != null) {
746 ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
747 }
748 }
749
750
751 @Override
752 protected Dialog onCreateDialog(int id) {
753 Dialog dialog = null;
754 AlertDialog.Builder builder;
755 switch (id) {
756 case DIALOG_SHORT_WAIT: {
757 ProgressDialog working_dialog = new ProgressDialog(this);
758 working_dialog.setMessage(getResources().getString(
759 R.string.wait_a_moment));
760 working_dialog.setIndeterminate(true);
761 working_dialog.setCancelable(false);
762 dialog = working_dialog;
763 break;
764 }
765 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
766
767 String[] items = null;
768
769 String[] allTheItems = { getString(R.string.actionbar_upload_files),
770 getString(R.string.actionbar_upload_from_apps),
771 getString(R.string.actionbar_failed_instant_upload) };
772
773 String[] commonItems = { getString(R.string.actionbar_upload_files),
774 getString(R.string.actionbar_upload_from_apps) };
775
776 if (InstantUploadActivity.IS_ENABLED)
777 items = allTheItems;
778 else
779 items = commonItems;
780
781 builder = new AlertDialog.Builder(this);
782 builder.setTitle(R.string.actionbar_upload);
783 builder.setItems(items, new DialogInterface.OnClickListener() {
784 public void onClick(DialogInterface dialog, int item) {
785 if (item == 0) {
786 // if (!mDualPane) {
787 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
788 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
789 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
790 // } else {
791 // TODO create and handle new fragment
792 // LocalFileListFragment
793 // }
794 } else if (item == 1) {
795 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
796 action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
797 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
798 ACTION_SELECT_CONTENT_FROM_APPS);
799 } else if (item == 2 && InstantUploadActivity.IS_ENABLED) {
800 Intent action = new Intent(FileDisplayActivity.this, InstantUploadActivity.class);
801 action.putExtra(FileUploader.KEY_ACCOUNT, FileDisplayActivity.this.getAccount());
802 startActivity(action);
803 }
804 }
805 });
806 dialog = builder.create();
807 break;
808 }
809 case DIALOG_SSL_VALIDATOR: {
810 dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
811 break;
812 }
813 case DIALOG_CERT_NOT_SAVED: {
814 builder = new AlertDialog.Builder(this);
815 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
816 builder.setCancelable(false);
817 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
818 @Override
819 public void onClick(DialogInterface dialog, int which) {
820 dialog.dismiss();
821 };
822 });
823 dialog = builder.create();
824 break;
825 }
826 default:
827 dialog = null;
828 }
829
830 return dialog;
831 }
832
833
834 /**
835 * Translates a content URI of an image to a physical path
836 * on the disk
837 * @param uri The URI to resolve
838 * @return The path to the image or null if it could not be found
839 */
840 public String getPath(Uri uri) {
841 String[] projection = { MediaStore.Images.Media.DATA };
842 Cursor cursor = managedQuery(uri, projection, null, null, null);
843 if (cursor != null) {
844 int column_index = cursor
845 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
846 cursor.moveToFirst();
847 return cursor.getString(column_index);
848 }
849 return null;
850 }
851
852 /**
853 * Pushes a directory to the drop down list
854 * @param directory to push
855 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
856 */
857 public void pushDirname(OCFile directory) {
858 if(!directory.isFolder()){
859 throw new IllegalArgumentException("Only directories may be pushed!");
860 }
861 mDirectories.insert(directory.getFileName(), 0);
862 setFile(directory);
863 }
864
865 /**
866 * Pops a directory name from the drop down list
867 * @return True, unless the stack is empty
868 */
869 public boolean popDirname() {
870 mDirectories.remove(mDirectories.getItem(0));
871 return !mDirectories.isEmpty();
872 }
873
874 // Custom array adapter to override text colors
875 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
876
877 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
878 super(ctx, view);
879 }
880
881 public View getView(int position, View convertView, ViewGroup parent) {
882 View v = super.getView(position, convertView, parent);
883
884 ((TextView) v).setTextColor(getResources().getColorStateList(
885 android.R.color.white));
886
887 fixRoot((TextView) v );
888 return v;
889 }
890
891 public View getDropDownView(int position, View convertView,
892 ViewGroup parent) {
893 View v = super.getDropDownView(position, convertView, parent);
894
895 ((TextView) v).setTextColor(getResources().getColorStateList(
896 android.R.color.white));
897
898 fixRoot((TextView) v );
899 return v;
900 }
901
902 private void fixRoot(TextView v) {
903 if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
904 v.setText(R.string.default_display_name_for_root_folder);
905 }
906 }
907
908 }
909
910 private class SyncBroadcastReceiver extends BroadcastReceiver {
911
912 /**
913 * {@link BroadcastReceiver} to enable syncing feedback in UI
914 */
915 @Override
916 public void onReceive(Context context, Intent intent) {
917 String event = intent.getAction();
918 Log_OC.d(TAG, "Received broadcast " + event);
919 String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
920 String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
921 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
922 boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
923
924 if (sameAccount) {
925
926 if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
927 mSyncInProgress = true;
928
929 } else {
930 OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
931 OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
932
933 if (currentDir == null) {
934 // current folder was removed from the server
935 Toast.makeText( FileDisplayActivity.this,
936 String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
937 Toast.LENGTH_LONG)
938 .show();
939 browseToRoot();
940
941 } else {
942 if (currentFile == null && !getFile().isFolder()) {
943 // currently selected file was removed in the server, and now we know it
944 cleanSecondFragment();
945 currentFile = currentDir;
946 }
947
948 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
949 OCFileListFragment fileListFragment = getListOfFilesFragment();
950 if (fileListFragment != null) {
951 fileListFragment.listDirectory(currentDir);
952 }
953 }
954 setFile(currentFile);
955 }
956
957 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
958
959 /*
960 if (synchResult != null &&
961 synchResult.isSuccess() &&
962 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
963 FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
964 ) &&
965 !mRefreshSharesInProgress &&
966 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
967 ) {
968 startGetShares();
969 }
970 */
971
972 }
973 removeStickyBroadcast(intent);
974 Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
975 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
976 }
977
978 if (synchResult != null) {
979 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
980 mLastSslUntrustedServerResult = synchResult;
981 showDialog(DIALOG_SSL_VALIDATOR);
982 }
983 }
984 }
985 }
986
987
988 private class UploadFinishReceiver extends BroadcastReceiver {
989 /**
990 * Once the file upload has finished -> update view
991 * @author David A. Velasco
992 * {@link BroadcastReceiver} to enable upload feedback in UI
993 */
994 @Override
995 public void onReceive(Context context, Intent intent) {
996 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
997 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
998 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
999 OCFile currentDir = getCurrentDir();
1000 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) && (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
1001 if (sameAccount && isDescendant) {
1002 refeshListOfFilesFragment();
1003 }
1004 }
1005
1006 }
1007
1008
1009 /**
1010 * Class waiting for broadcast events from the {@link FielDownloader} service.
1011 *
1012 * Updates the UI when a download is started or finished, provided that it is relevant for the
1013 * current folder.
1014 */
1015 private class DownloadFinishReceiver extends BroadcastReceiver {
1016 @Override
1017 public void onReceive(Context context, Intent intent) {
1018 boolean sameAccount = isSameAccount(context, intent);
1019 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1020 boolean isDescendant = isDescendant(downloadedRemotePath);
1021
1022 if (sameAccount && isDescendant) {
1023 refeshListOfFilesFragment();
1024 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1025 }
1026
1027 if (mWaitingToSend != null && mWaitingToSend.isDown()) {
1028
1029 sendDownloadedFile();
1030
1031 }
1032 removeStickyBroadcast(intent);
1033 }
1034
1035 private boolean isDescendant(String downloadedRemotePath) {
1036 OCFile currentDir = getCurrentDir();
1037 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
1038 }
1039
1040 private boolean isSameAccount(Context context, Intent intent) {
1041 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1042 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1043 }
1044 }
1045
1046
1047 /**
1048 * Class waiting for broadcast events from the {@link OperationsService}.
1049 *
1050 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1051 * operation performed in {@link OperationsService}.
1052 *
1053 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1054 * probably all the operations associated to the app model.
1055 */
1056 private class OperationsServiceReceiver extends BroadcastReceiver {
1057
1058 @Override
1059 public void onReceive(Context context, Intent intent) {
1060 if (OperationsService.ACTION_OPERATION_ADDED.equals(intent.getAction())) {
1061
1062 } else if (OperationsService.ACTION_OPERATION_FINISHED.equals(intent.getAction())) {
1063 //mRefreshSharesInProgress = false;
1064
1065 Account account = intent.getParcelableExtra(OperationsService.EXTRA_ACCOUNT);
1066 RemoteOperationResult getSharesResult = (RemoteOperationResult)intent.getSerializableExtra(OperationsService.EXTRA_RESULT);
1067 if (getAccount() != null && account.name.equals(getAccount().name)
1068 && getStorageManager() != null
1069 ) {
1070 refeshListOfFilesFragment();
1071 }
1072 if ((getSharesResult != null) &&
1073 RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(getSharesResult.getCode())) {
1074 mLastSslUntrustedServerResult = getSharesResult;
1075 showDialog(DIALOG_SSL_VALIDATOR);
1076 }
1077
1078 //setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
1079 }
1080
1081 }
1082
1083 }
1084
1085 public void browseToRoot() {
1086 OCFileListFragment listOfFiles = getListOfFilesFragment();
1087 if (listOfFiles != null) { // should never be null, indeed
1088 while (mDirectories.getCount() > 1) {
1089 popDirname();
1090 }
1091 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1092 listOfFiles.listDirectory(root);
1093 setFile(listOfFiles.getCurrentFile());
1094 startSyncFolderOperation(root);
1095 }
1096 cleanSecondFragment();
1097 }
1098
1099
1100 public void browseTo(OCFile folder) {
1101 if (folder == null || !folder.isFolder()) {
1102 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1103 }
1104 OCFileListFragment listOfFiles = getListOfFilesFragment();
1105 if (listOfFiles != null) {
1106 setNavigationListWithFolder(folder);
1107 listOfFiles.listDirectory(folder);
1108 setFile(listOfFiles.getCurrentFile());
1109 startSyncFolderOperation(folder);
1110 } else {
1111 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1112 }
1113 cleanSecondFragment();
1114 }
1115
1116
1117 /**
1118 * {@inheritDoc}
1119 *
1120 * Updates action bar and second fragment, if in dual pane mode.
1121 */
1122 @Override
1123 public void onBrowsedDownTo(OCFile directory) {
1124 pushDirname(directory);
1125 cleanSecondFragment();
1126
1127 // Sync Folder
1128 startSyncFolderOperation(directory);
1129
1130 }
1131
1132 /**
1133 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1134 *
1135 * @param file Image {@link OCFile} to show.
1136 */
1137 @Override
1138 public void startImagePreview(OCFile file) {
1139 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1140 showDetailsIntent.putExtra(EXTRA_FILE, file);
1141 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1142 startActivity(showDetailsIntent);
1143 }
1144
1145 /**
1146 * Stars the preview of an already down media {@link OCFile}.
1147 *
1148 * @param file Media {@link OCFile} to preview.
1149 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1150 * @param autoplay When 'true', the playback will start without user interactions.
1151 */
1152 @Override
1153 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1154 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1155 setSecondFragment(mediaFragment);
1156 updateFragmentsVisibility(true);
1157 updateNavigationElementsInActionBar(file);
1158 setFile(file);
1159 }
1160
1161 /**
1162 * Requests the download of the received {@link OCFile} , updates the UI
1163 * to monitor the download progress and prepares the activity to preview
1164 * or open the file when the download finishes.
1165 *
1166 * @param file {@link OCFile} to download and preview.
1167 */
1168 @Override
1169 public void startDownloadForPreview(OCFile file) {
1170 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1171 setSecondFragment(detailFragment);
1172 mWaitingToPreview = file;
1173 requestForDownload();
1174 updateFragmentsVisibility(true);
1175 updateNavigationElementsInActionBar(file);
1176 setFile(file);
1177 }
1178
1179
1180 /**
1181 * Shows the information of the {@link OCFile} received as a
1182 * parameter in the second fragment.
1183 *
1184 * @param file {@link OCFile} whose details will be shown
1185 */
1186 @Override
1187 public void showDetails(OCFile file) {
1188 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1189 setSecondFragment(detailFragment);
1190 updateFragmentsVisibility(true);
1191 updateNavigationElementsInActionBar(file);
1192 setFile(file);
1193 }
1194
1195
1196 /**
1197 * TODO
1198 */
1199 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1200 ActionBar actionBar = getSupportActionBar();
1201 if (chosenFile == null || mDualPane) {
1202 // only list of files - set for browsing through folders
1203 OCFile currentDir = getCurrentDir();
1204 boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
1205 actionBar.setDisplayHomeAsUpEnabled(noRoot);
1206 actionBar.setDisplayShowTitleEnabled(!noRoot);
1207 if (!noRoot) {
1208 actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
1209 }
1210 actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
1211 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1212
1213 } else {
1214 actionBar.setDisplayHomeAsUpEnabled(true);
1215 actionBar.setDisplayShowTitleEnabled(true);
1216 actionBar.setTitle(chosenFile.getFileName());
1217 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1218 }
1219 }
1220
1221
1222 /**
1223 * {@inheritDoc}
1224 */
1225 @Override
1226 public void onFileStateChanged() {
1227 refeshListOfFilesFragment();
1228 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1229 }
1230
1231
1232 /**
1233 * {@inheritDoc}
1234 */
1235 @Override
1236 public FileDownloaderBinder getFileDownloaderBinder() {
1237 return mDownloaderBinder;
1238 }
1239
1240
1241 /**
1242 * {@inheritDoc}
1243 */
1244 @Override
1245 public FileUploaderBinder getFileUploaderBinder() {
1246 return mUploaderBinder;
1247 }
1248
1249
1250 /** Defines callbacks for service binding, passed to bindService() */
1251 private class ListServiceConnection implements ServiceConnection {
1252
1253 @Override
1254 public void onServiceConnected(ComponentName component, IBinder service) {
1255 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1256 Log_OC.d(TAG, "Download service connected");
1257 mDownloaderBinder = (FileDownloaderBinder) service;
1258 if (mWaitingToPreview != null) {
1259 requestForDownload();
1260 }
1261
1262 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1263 Log_OC.d(TAG, "Upload service connected");
1264 mUploaderBinder = (FileUploaderBinder) service;
1265 } else {
1266 return;
1267 }
1268 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1269 OCFileListFragment listOfFiles = getListOfFilesFragment();
1270 if (listOfFiles != null) {
1271 listOfFiles.listDirectory();
1272 }
1273 FileFragment secondFragment = getSecondFragment();
1274 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1275 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1276 detailFragment.listenForTransferProgress();
1277 detailFragment.updateFileDetails(false, false);
1278 }
1279 }
1280
1281 @Override
1282 public void onServiceDisconnected(ComponentName component) {
1283 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1284 Log_OC.d(TAG, "Download service disconnected");
1285 mDownloaderBinder = null;
1286 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1287 Log_OC.d(TAG, "Upload service disconnected");
1288 mUploaderBinder = null;
1289 }
1290 }
1291 };
1292
1293
1294
1295 /**
1296 * Launch an intent to request the PIN code to the user before letting him use the app
1297 */
1298 private void requestPinCode() {
1299 boolean pinStart = false;
1300 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1301 pinStart = appPrefs.getBoolean("set_pincode", false);
1302 if (pinStart) {
1303 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1304 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1305 startActivity(i);
1306 }
1307 }
1308
1309
1310 @Override
1311 public void onSavedCertificate() {
1312 startSyncFolderOperation(getCurrentDir());
1313 }
1314
1315
1316 @Override
1317 public void onFailedSavingCertificate() {
1318 showDialog(DIALOG_CERT_NOT_SAVED);
1319 }
1320
1321
1322 /**
1323 * Updates the view associated to the activity after the finish of some operation over files
1324 * in the current account.
1325 *
1326 * @param operation Removal operation performed.
1327 * @param result Result of the removal.
1328 */
1329 @Override
1330 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1331 super.onRemoteOperationFinish(operation, result);
1332
1333 if (operation instanceof RemoveFileOperation) {
1334 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1335
1336 } else if (operation instanceof RenameFileOperation) {
1337 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1338
1339 } else if (operation instanceof SynchronizeFileOperation) {
1340 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1341
1342 } else if (operation instanceof CreateFolderOperation) {
1343 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1344
1345 } else if (operation instanceof CreateShareOperation) {
1346 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1347
1348 } else if (operation instanceof UnshareLinkOperation) {
1349 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
1350
1351 }
1352
1353 }
1354
1355
1356 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
1357 if (result.isSuccess()) {
1358 refreshShowDetails();
1359 refeshListOfFilesFragment();
1360 }
1361 }
1362
1363
1364 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
1365 if (result.isSuccess()) {
1366 refreshShowDetails();
1367 refeshListOfFilesFragment();
1368 } else if (result.getCode() == ResultCode.SHARE_NOT_FOUND) {
1369 cleanSecondFragment();
1370 refeshListOfFilesFragment();
1371 }
1372 }
1373
1374 private void refreshShowDetails() {
1375 FileFragment details = getSecondFragment();
1376 if (details != null) {
1377 OCFile file = details.getFile();
1378 if (file != null) {
1379 file = getStorageManager().getFileByPath(file.getRemotePath());
1380 if (details instanceof PreviewMediaFragment) {
1381 // Refresh OCFile of the fragment
1382 ((PreviewMediaFragment) details).updateFile(file);
1383 } else {
1384 showDetails(file);
1385 }
1386 }
1387 invalidateOptionsMenu();
1388 }
1389 }
1390
1391 /**
1392 * Updates the view associated to the activity after the finish of an operation trying to remove a
1393 * file.
1394 *
1395 * @param operation Removal operation performed.
1396 * @param result Result of the removal.
1397 */
1398 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1399 dismissLoadingDialog();
1400 if (result.isSuccess()) {
1401 Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
1402 msg.show();
1403 OCFile removedFile = operation.getFile();
1404 getSecondFragment();
1405 FileFragment second = getSecondFragment();
1406 if (second != null && removedFile.equals(second.getFile())) {
1407 cleanSecondFragment();
1408 }
1409 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1410 refeshListOfFilesFragment();
1411 }
1412
1413 } else {
1414 Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
1415 msg.show();
1416 if (result.isSslRecoverableException()) {
1417 mLastSslUntrustedServerResult = result;
1418 showDialog(DIALOG_SSL_VALIDATOR);
1419 }
1420 }
1421 }
1422
1423 /**
1424 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1425 *
1426 * @param operation Creation operation performed.
1427 * @param result Result of the creation.
1428 */
1429 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1430 if (result.isSuccess()) {
1431 dismissLoadingDialog();
1432 refeshListOfFilesFragment();
1433
1434 } else {
1435 dismissLoadingDialog();
1436 if (result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME) {
1437 Toast.makeText(FileDisplayActivity.this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG).show();
1438 } else {
1439 try {
1440 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
1441 msg.show();
1442
1443 } catch (NotFoundException e) {
1444 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1445 }
1446 }
1447 }
1448 }
1449
1450
1451 /**
1452 * Updates the view associated to the activity after the finish of an operation trying to rename a
1453 * file.
1454 *
1455 * @param operation Renaming operation performed.
1456 * @param result Result of the renaming.
1457 */
1458 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1459 dismissLoadingDialog();
1460 OCFile renamedFile = operation.getFile();
1461 if (result.isSuccess()) {
1462 if (mDualPane) {
1463 FileFragment details = getSecondFragment();
1464 if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1465 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1466 }
1467 }
1468 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1469 refeshListOfFilesFragment();
1470 }
1471
1472 } else {
1473 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1474 Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1475 msg.show();
1476 // TODO throw again the new rename dialog
1477 } if (result.getCode().equals(ResultCode.INVALID_CHARACTER_IN_NAME)) {
1478 Toast msg = Toast.makeText(this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG);
1479 msg.show();
1480 } else {
1481 Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1482 msg.show();
1483 if (result.isSslRecoverableException()) {
1484 mLastSslUntrustedServerResult = result;
1485 showDialog(DIALOG_SSL_VALIDATOR);
1486 }
1487 }
1488 }
1489 }
1490
1491
1492 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1493 dismissLoadingDialog();
1494 OCFile syncedFile = operation.getLocalFile();
1495 if (!result.isSuccess()) {
1496 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1497 Intent i = new Intent(this, ConflictsResolveActivity.class);
1498 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1499 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1500 startActivity(i);
1501
1502 }
1503
1504 } else {
1505 if (operation.transferWasRequested()) {
1506 refeshListOfFilesFragment();
1507 onTransferStateChanged(syncedFile, true, true);
1508
1509 } else {
1510 Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1511 msg.show();
1512 }
1513 }
1514 }
1515
1516
1517 /**
1518 * {@inheritDoc}
1519 */
1520 @Override
1521 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1522 if (mDualPane) {
1523 FileFragment details = getSecondFragment();
1524 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1525 if (downloading || uploading) {
1526 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1527 } else {
1528 ((FileDetailFragment)details).updateFileDetails(false, true);
1529 }
1530 }
1531 }
1532 }
1533
1534
1535 public void onDismiss(EditNameDialog dialog) {
1536 if (dialog.getResult()) {
1537 String newDirectoryName = dialog.getNewFilename().trim();
1538 Log_OC.d(TAG, "'create directory' dialog dismissed with new name " + newDirectoryName);
1539 if (newDirectoryName.length() > 0) {
1540 String path = getCurrentDir().getRemotePath();
1541
1542 // Create directory
1543 path += newDirectoryName + OCFile.PATH_SEPARATOR;
1544 RemoteOperation operation = new CreateFolderOperation(path, false, getStorageManager());
1545 operation.execute( getAccount(),
1546 FileDisplayActivity.this,
1547 FileDisplayActivity.this,
1548 getHandler(),
1549 FileDisplayActivity.this);
1550
1551 showLoadingDialog();
1552 }
1553 }
1554 }
1555
1556
1557 private void requestForDownload() {
1558 Account account = getAccount();
1559 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1560 Intent i = new Intent(this, FileDownloader.class);
1561 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1562 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1563 startService(i);
1564 }
1565 }
1566
1567
1568 private OCFile getCurrentDir() {
1569 OCFile file = getFile();
1570 if (file != null) {
1571 if (file.isFolder()) {
1572 return file;
1573 } else if (getStorageManager() != null) {
1574 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
1575 return getStorageManager().getFileByPath(parentPath);
1576 }
1577 }
1578 return null;
1579 }
1580
1581 public void startSyncFolderOperation(OCFile folder) {
1582 long currentSyncTime = System.currentTimeMillis();
1583
1584 mSyncInProgress = true;
1585
1586 // perform folder synchronization
1587 RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
1588 currentSyncTime,
1589 false,
1590 getFileOperationsHelper().isSharedSupported(this),
1591 getStorageManager(),
1592 getAccount(),
1593 getApplicationContext()
1594 );
1595 synchFolderOp.execute(getAccount(), this, null, null, this);
1596
1597 setSupportProgressBarIndeterminateVisibility(true);
1598 }
1599
1600 /*
1601 private void startGetShares() {
1602 // Get shared files/folders
1603 Intent intent = new Intent(this, OperationsService.class);
1604 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1605 startService(intent);
1606
1607 mRefreshSharesInProgress = true;
1608 }
1609 */
1610
1611 /**
1612 * Requests the download of the received {@link OCFile} , updates the UI
1613 * to monitor the download progress and prepares the activity to send the file
1614 * when the download finishes.
1615 *
1616 * @param file {@link OCFile} to download and preview.
1617 */
1618 @Override
1619 public void startDownloadForSending(OCFile file) {
1620 mWaitingToSend = file;
1621 requestForDownload(mWaitingToSend);
1622 updateFragmentsVisibility(true);
1623 }
1624
1625 private void requestForDownload(OCFile file) {
1626 Account account = getAccount();
1627 if (!mDownloaderBinder.isDownloading(account, file)) {
1628 Intent i = new Intent(this, FileDownloader.class);
1629 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1630 i.putExtra(FileDownloader.EXTRA_FILE, file);
1631 startService(i);
1632 }
1633 }
1634
1635 private void sendDownloadedFile(){
1636 getFileOperationsHelper().sendDownloadedFile(mWaitingToSend, this);
1637 mWaitingToSend = null;
1638 }
1639
1640 }