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