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