OC-2868: Fix bug: Unshare a file that does not exist any more, no message is shown
[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_FULL_SYNC_FOLDER_SIZE_SYNCED);
679 syncIntentFilter.addAction(FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED);
680 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
681 syncIntentFilter.addAction(SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
682 mSyncBroadcastReceiver = new SyncBroadcastReceiver();
683 registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
684 //LocalBroadcastManager.getInstance(this).registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
685
686 // Listen for upload messages
687 IntentFilter uploadIntentFilter = new IntentFilter(FileUploader.getUploadFinishMessage());
688 mUploadFinishReceiver = new UploadFinishReceiver();
689 registerReceiver(mUploadFinishReceiver, uploadIntentFilter);
690
691 // Listen for download messages
692 IntentFilter downloadIntentFilter = new IntentFilter(FileDownloader.getDownloadAddedMessage());
693 downloadIntentFilter.addAction(FileDownloader.getDownloadFinishMessage());
694 mDownloadFinishReceiver = new DownloadFinishReceiver();
695 registerReceiver(mDownloadFinishReceiver, downloadIntentFilter);
696
697 // Listen for messages from the OperationsService
698 /*
699 IntentFilter operationsIntentFilter = new IntentFilter(OperationsService.ACTION_OPERATION_ADDED);
700 operationsIntentFilter.addAction(OperationsService.ACTION_OPERATION_FINISHED);
701 mOperationsServiceReceiver = new OperationsServiceReceiver();
702 LocalBroadcastManager.getInstance(this).registerReceiver(mOperationsServiceReceiver, operationsIntentFilter);
703 */
704
705 Log_OC.d(TAG, "onResume() end");
706 }
707
708
709 @Override
710 protected void onPause() {
711 super.onPause();
712 Log_OC.e(TAG, "onPause() start");
713 if (mSyncBroadcastReceiver != null) {
714 unregisterReceiver(mSyncBroadcastReceiver);
715 //LocalBroadcastManager.getInstance(this).unregisterReceiver(mSyncBroadcastReceiver);
716 mSyncBroadcastReceiver = null;
717 }
718 if (mUploadFinishReceiver != null) {
719 unregisterReceiver(mUploadFinishReceiver);
720 mUploadFinishReceiver = null;
721 }
722 if (mDownloadFinishReceiver != null) {
723 unregisterReceiver(mDownloadFinishReceiver);
724 mDownloadFinishReceiver = null;
725 }
726 /*
727 if (mOperationsServiceReceiver != null) {
728 LocalBroadcastManager.getInstance(this).unregisterReceiver(mOperationsServiceReceiver);
729 mOperationsServiceReceiver = null;
730 }
731 */
732 Log_OC.d(TAG, "onPause() end");
733 }
734
735
736 @Override
737 protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
738 if (id == DIALOG_SSL_VALIDATOR && mLastSslUntrustedServerResult != null) {
739 ((SslValidatorDialog)dialog).updateResult(mLastSslUntrustedServerResult);
740 }
741 }
742
743
744 @Override
745 protected Dialog onCreateDialog(int id) {
746 Dialog dialog = null;
747 AlertDialog.Builder builder;
748 switch (id) {
749 case DIALOG_SHORT_WAIT: {
750 ProgressDialog working_dialog = new ProgressDialog(this);
751 working_dialog.setMessage(getResources().getString(
752 R.string.wait_a_moment));
753 working_dialog.setIndeterminate(true);
754 working_dialog.setCancelable(false);
755 dialog = working_dialog;
756 break;
757 }
758 case DIALOG_CHOOSE_UPLOAD_SOURCE: {
759
760 String[] items = null;
761
762 String[] allTheItems = { getString(R.string.actionbar_upload_files),
763 getString(R.string.actionbar_upload_from_apps),
764 getString(R.string.actionbar_failed_instant_upload) };
765
766 String[] commonItems = { getString(R.string.actionbar_upload_files),
767 getString(R.string.actionbar_upload_from_apps) };
768
769 if (InstantUploadActivity.IS_ENABLED)
770 items = allTheItems;
771 else
772 items = commonItems;
773
774 builder = new AlertDialog.Builder(this);
775 builder.setTitle(R.string.actionbar_upload);
776 builder.setItems(items, new DialogInterface.OnClickListener() {
777 public void onClick(DialogInterface dialog, int item) {
778 if (item == 0) {
779 // if (!mDualPane) {
780 Intent action = new Intent(FileDisplayActivity.this, UploadFilesActivity.class);
781 action.putExtra(UploadFilesActivity.EXTRA_ACCOUNT, FileDisplayActivity.this.getAccount());
782 startActivityForResult(action, ACTION_SELECT_MULTIPLE_FILES);
783 // } else {
784 // TODO create and handle new fragment
785 // LocalFileListFragment
786 // }
787 } else if (item == 1) {
788 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
789 action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
790 startActivityForResult(Intent.createChooser(action, getString(R.string.upload_chooser_title)),
791 ACTION_SELECT_CONTENT_FROM_APPS);
792 } else if (item == 2 && InstantUploadActivity.IS_ENABLED) {
793 Intent action = new Intent(FileDisplayActivity.this, InstantUploadActivity.class);
794 action.putExtra(FileUploader.KEY_ACCOUNT, FileDisplayActivity.this.getAccount());
795 startActivity(action);
796 }
797 }
798 });
799 dialog = builder.create();
800 break;
801 }
802 case DIALOG_SSL_VALIDATOR: {
803 dialog = SslValidatorDialog.newInstance(this, mLastSslUntrustedServerResult, this);
804 break;
805 }
806 case DIALOG_CERT_NOT_SAVED: {
807 builder = new AlertDialog.Builder(this);
808 builder.setMessage(getResources().getString(R.string.ssl_validator_not_saved));
809 builder.setCancelable(false);
810 builder.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {
811 @Override
812 public void onClick(DialogInterface dialog, int which) {
813 dialog.dismiss();
814 };
815 });
816 dialog = builder.create();
817 break;
818 }
819 default:
820 dialog = null;
821 }
822
823 return dialog;
824 }
825
826
827 /**
828 * Translates a content URI of an image to a physical path
829 * on the disk
830 * @param uri The URI to resolve
831 * @return The path to the image or null if it could not be found
832 */
833 public String getPath(Uri uri) {
834 String[] projection = { MediaStore.Images.Media.DATA };
835 Cursor cursor = managedQuery(uri, projection, null, null, null);
836 if (cursor != null) {
837 int column_index = cursor
838 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
839 cursor.moveToFirst();
840 return cursor.getString(column_index);
841 }
842 return null;
843 }
844
845 /**
846 * Pushes a directory to the drop down list
847 * @param directory to push
848 * @throws IllegalArgumentException If the {@link OCFile#isFolder()} returns false.
849 */
850 public void pushDirname(OCFile directory) {
851 if(!directory.isFolder()){
852 throw new IllegalArgumentException("Only directories may be pushed!");
853 }
854 mDirectories.insert(directory.getFileName(), 0);
855 setFile(directory);
856 }
857
858 /**
859 * Pops a directory name from the drop down list
860 * @return True, unless the stack is empty
861 */
862 public boolean popDirname() {
863 mDirectories.remove(mDirectories.getItem(0));
864 return !mDirectories.isEmpty();
865 }
866
867 // Custom array adapter to override text colors
868 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
869
870 public CustomArrayAdapter(FileDisplayActivity ctx, int view) {
871 super(ctx, view);
872 }
873
874 public View getView(int position, View convertView, ViewGroup parent) {
875 View v = super.getView(position, convertView, parent);
876
877 ((TextView) v).setTextColor(getResources().getColorStateList(
878 android.R.color.white));
879
880 fixRoot((TextView) v );
881 return v;
882 }
883
884 public View getDropDownView(int position, View convertView,
885 ViewGroup parent) {
886 View v = super.getDropDownView(position, convertView, parent);
887
888 ((TextView) v).setTextColor(getResources().getColorStateList(
889 android.R.color.white));
890
891 fixRoot((TextView) v );
892 return v;
893 }
894
895 private void fixRoot(TextView v) {
896 if (v.getText().equals(OCFile.PATH_SEPARATOR)) {
897 v.setText(R.string.default_display_name_for_root_folder);
898 }
899 }
900
901 }
902
903 private class SyncBroadcastReceiver extends BroadcastReceiver {
904
905 /**
906 * {@link BroadcastReceiver} to enable syncing feedback in UI
907 */
908 @Override
909 public void onReceive(Context context, Intent intent) {
910 String event = intent.getAction();
911 Log_OC.d(TAG, "Received broadcast " + event);
912 String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
913 String synchFolderRemotePath = intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
914 RemoteOperationResult synchResult = (RemoteOperationResult)intent.getSerializableExtra(FileSyncAdapter.EXTRA_RESULT);
915 boolean sameAccount = (getAccount() != null && accountName.equals(getAccount().name) && getStorageManager() != null);
916
917 if (sameAccount) {
918
919 if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
920 mSyncInProgress = true;
921
922 } else {
923 OCFile currentFile = (getFile() == null) ? null : getStorageManager().getFileByPath(getFile().getRemotePath());
924 OCFile currentDir = (getCurrentDir() == null) ? null : getStorageManager().getFileByPath(getCurrentDir().getRemotePath());
925
926 if (currentDir == null) {
927 // current folder was removed from the server
928 Toast.makeText( FileDisplayActivity.this,
929 String.format(getString(R.string.sync_current_folder_was_removed), mDirectories.getItem(0)),
930 Toast.LENGTH_LONG)
931 .show();
932 browseToRoot();
933
934 } else {
935 if (currentFile == null && !getFile().isFolder()) {
936 // currently selected file was removed in the server, and now we know it
937 cleanSecondFragment();
938 currentFile = currentDir;
939 }
940
941 if (synchFolderRemotePath != null && currentDir.getRemotePath().equals(synchFolderRemotePath)) {
942 OCFileListFragment fileListFragment = getListOfFilesFragment();
943 if (fileListFragment != null) {
944 fileListFragment.listDirectory(currentDir);
945 }
946 }
947 setFile(currentFile);
948 }
949
950 mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) && !SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
951
952 /*
953 if (synchResult != null &&
954 synchResult.isSuccess() &&
955 (SynchronizeFolderOperation.EVENT_SINGLE_FOLDER_SYNCED.equals(event) ||
956 FileSyncAdapter.EVENT_FULL_SYNC_FOLDER_CONTENTS_SYNCED.equals(event)
957 ) &&
958 !mRefreshSharesInProgress &&
959 getFileOperationsHelper().isSharedSupported(FileDisplayActivity.this)
960 ) {
961 startGetShares();
962 }
963 */
964
965 }
966 removeStickyBroadcast(intent);
967 Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
968 setSupportProgressBarIndeterminateVisibility(mSyncInProgress /*|| mRefreshSharesInProgress*/);
969 }
970
971 if (synchResult != null) {
972 if (synchResult.getCode().equals(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED)) {
973 mLastSslUntrustedServerResult = synchResult;
974 showDialog(DIALOG_SSL_VALIDATOR);
975 }
976 }
977 }
978 }
979
980
981 private class UploadFinishReceiver extends BroadcastReceiver {
982 /**
983 * Once the file upload has finished -> update view
984 * @author David A. Velasco
985 * {@link BroadcastReceiver} to enable upload feedback in UI
986 */
987 @Override
988 public void onReceive(Context context, Intent intent) {
989 String uploadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
990 String accountName = intent.getStringExtra(FileUploader.ACCOUNT_NAME);
991 boolean sameAccount = getAccount() != null && accountName.equals(getAccount().name);
992 OCFile currentDir = getCurrentDir();
993 boolean isDescendant = (currentDir != null) && (uploadedRemotePath != null) && (uploadedRemotePath.startsWith(currentDir.getRemotePath()));
994 if (sameAccount && isDescendant) {
995 refeshListOfFilesFragment();
996 }
997 }
998
999 }
1000
1001
1002 /**
1003 * Class waiting for broadcast events from the {@link FielDownloader} service.
1004 *
1005 * Updates the UI when a download is started or finished, provided that it is relevant for the
1006 * current folder.
1007 */
1008 private class DownloadFinishReceiver extends BroadcastReceiver {
1009 @Override
1010 public void onReceive(Context context, Intent intent) {
1011 boolean sameAccount = isSameAccount(context, intent);
1012 String downloadedRemotePath = intent.getStringExtra(FileDownloader.EXTRA_REMOTE_PATH);
1013 boolean isDescendant = isDescendant(downloadedRemotePath);
1014
1015 if (sameAccount && isDescendant) {
1016 refeshListOfFilesFragment();
1017 refreshSecondFragment(intent.getAction(), downloadedRemotePath, intent.getBooleanExtra(FileDownloader.EXTRA_DOWNLOAD_RESULT, false));
1018 }
1019
1020 removeStickyBroadcast(intent);
1021 }
1022
1023 private boolean isDescendant(String downloadedRemotePath) {
1024 OCFile currentDir = getCurrentDir();
1025 return (currentDir != null && downloadedRemotePath != null && downloadedRemotePath.startsWith(currentDir.getRemotePath()));
1026 }
1027
1028 private boolean isSameAccount(Context context, Intent intent) {
1029 String accountName = intent.getStringExtra(FileDownloader.ACCOUNT_NAME);
1030 return (accountName != null && getAccount() != null && accountName.equals(getAccount().name));
1031 }
1032 }
1033
1034
1035 /**
1036 * Class waiting for broadcast events from the {@link OperationsService}.
1037 *
1038 * Updates the list of files when a get for shares is finished; at this moment the refresh of shares is the only
1039 * operation performed in {@link OperationsService}.
1040 *
1041 * In the future will handle the progress or finalization of all the operations performed in {@link OperationsService},
1042 * probably all the operations associated to the app model.
1043 */
1044 private class OperationsServiceReceiver extends BroadcastReceiver {
1045
1046 @Override
1047 public void onReceive(Context context, Intent intent) {
1048 if (OperationsService.ACTION_OPERATION_ADDED.equals(intent.getAction())) {
1049
1050 } else if (OperationsService.ACTION_OPERATION_FINISHED.equals(intent.getAction())) {
1051 //mRefreshSharesInProgress = false;
1052
1053 Account account = intent.getParcelableExtra(OperationsService.EXTRA_ACCOUNT);
1054 RemoteOperationResult getSharesResult = (RemoteOperationResult)intent.getSerializableExtra(OperationsService.EXTRA_RESULT);
1055 if (getAccount() != null && account.name.equals(getAccount().name)
1056 && getStorageManager() != null
1057 ) {
1058 refeshListOfFilesFragment();
1059 }
1060 if ((getSharesResult != null) &&
1061 RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(getSharesResult.getCode())) {
1062 mLastSslUntrustedServerResult = getSharesResult;
1063 showDialog(DIALOG_SSL_VALIDATOR);
1064 }
1065
1066 //setSupportProgressBarIndeterminateVisibility(mRefreshSharesInProgress || mSyncInProgress);
1067 }
1068
1069 }
1070
1071 }
1072
1073 public void browseToRoot() {
1074 OCFileListFragment listOfFiles = getListOfFilesFragment();
1075 if (listOfFiles != null) { // should never be null, indeed
1076 while (mDirectories.getCount() > 1) {
1077 popDirname();
1078 }
1079 OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
1080 listOfFiles.listDirectory(root);
1081 setFile(listOfFiles.getCurrentFile());
1082 startSyncFolderOperation(root);
1083 }
1084 cleanSecondFragment();
1085 }
1086
1087
1088 public void browseTo(OCFile folder) {
1089 if (folder == null || !folder.isFolder()) {
1090 throw new IllegalArgumentException("Trying to browse to invalid folder " + folder);
1091 }
1092 OCFileListFragment listOfFiles = getListOfFilesFragment();
1093 if (listOfFiles != null) {
1094 setNavigationListWithFolder(folder);
1095 listOfFiles.listDirectory(folder);
1096 setFile(listOfFiles.getCurrentFile());
1097 startSyncFolderOperation(folder);
1098 } else {
1099 Log_OC.e(TAG, "Unexpected null when accessing list fragment");
1100 }
1101 cleanSecondFragment();
1102 }
1103
1104
1105 /**
1106 * {@inheritDoc}
1107 *
1108 * Updates action bar and second fragment, if in dual pane mode.
1109 */
1110 @Override
1111 public void onBrowsedDownTo(OCFile directory) {
1112 pushDirname(directory);
1113 cleanSecondFragment();
1114
1115 // Sync Folder
1116 startSyncFolderOperation(directory);
1117
1118 }
1119
1120 /**
1121 * Opens the image gallery showing the image {@link OCFile} received as parameter.
1122 *
1123 * @param file Image {@link OCFile} to show.
1124 */
1125 @Override
1126 public void startImagePreview(OCFile file) {
1127 Intent showDetailsIntent = new Intent(this, PreviewImageActivity.class);
1128 showDetailsIntent.putExtra(EXTRA_FILE, file);
1129 showDetailsIntent.putExtra(EXTRA_ACCOUNT, getAccount());
1130 startActivity(showDetailsIntent);
1131 }
1132
1133 /**
1134 * Stars the preview of an already down media {@link OCFile}.
1135 *
1136 * @param file Media {@link OCFile} to preview.
1137 * @param startPlaybackPosition Media position where the playback will be started, in milliseconds.
1138 * @param autoplay When 'true', the playback will start without user interactions.
1139 */
1140 @Override
1141 public void startMediaPreview(OCFile file, int startPlaybackPosition, boolean autoplay) {
1142 Fragment mediaFragment = new PreviewMediaFragment(file, getAccount(), startPlaybackPosition, autoplay);
1143 setSecondFragment(mediaFragment);
1144 updateFragmentsVisibility(true);
1145 updateNavigationElementsInActionBar(file);
1146 setFile(file);
1147 }
1148
1149 /**
1150 * Requests the download of the received {@link OCFile} , updates the UI
1151 * to monitor the download progress and prepares the activity to preview
1152 * or open the file when the download finishes.
1153 *
1154 * @param file {@link OCFile} to download and preview.
1155 */
1156 @Override
1157 public void startDownloadForPreview(OCFile file) {
1158 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1159 setSecondFragment(detailFragment);
1160 mWaitingToPreview = file;
1161 requestForDownload();
1162 updateFragmentsVisibility(true);
1163 updateNavigationElementsInActionBar(file);
1164 setFile(file);
1165 }
1166
1167
1168 /**
1169 * Shows the information of the {@link OCFile} received as a
1170 * parameter in the second fragment.
1171 *
1172 * @param file {@link OCFile} whose details will be shown
1173 */
1174 @Override
1175 public void showDetails(OCFile file) {
1176 Fragment detailFragment = new FileDetailFragment(file, getAccount());
1177 setSecondFragment(detailFragment);
1178 updateFragmentsVisibility(true);
1179 updateNavigationElementsInActionBar(file);
1180 setFile(file);
1181 }
1182
1183
1184 /**
1185 * TODO
1186 */
1187 private void updateNavigationElementsInActionBar(OCFile chosenFile) {
1188 ActionBar actionBar = getSupportActionBar();
1189 if (chosenFile == null || mDualPane) {
1190 // only list of files - set for browsing through folders
1191 OCFile currentDir = getCurrentDir();
1192 boolean noRoot = (currentDir != null && currentDir.getParentId() != 0);
1193 actionBar.setDisplayHomeAsUpEnabled(noRoot);
1194 actionBar.setDisplayShowTitleEnabled(!noRoot);
1195 if (!noRoot) {
1196 actionBar.setTitle(getString(R.string.default_display_name_for_root_folder));
1197 }
1198 actionBar.setNavigationMode(!noRoot ? ActionBar.NAVIGATION_MODE_STANDARD : ActionBar.NAVIGATION_MODE_LIST);
1199 actionBar.setListNavigationCallbacks(mDirectories, this); // assuming mDirectories is updated
1200
1201 } else {
1202 actionBar.setDisplayHomeAsUpEnabled(true);
1203 actionBar.setDisplayShowTitleEnabled(true);
1204 actionBar.setTitle(chosenFile.getFileName());
1205 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
1206 }
1207 }
1208
1209
1210 /**
1211 * {@inheritDoc}
1212 */
1213 @Override
1214 public void onFileStateChanged() {
1215 refeshListOfFilesFragment();
1216 updateNavigationElementsInActionBar(getSecondFragment().getFile());
1217 }
1218
1219
1220 /**
1221 * {@inheritDoc}
1222 */
1223 @Override
1224 public FileDownloaderBinder getFileDownloaderBinder() {
1225 return mDownloaderBinder;
1226 }
1227
1228
1229 /**
1230 * {@inheritDoc}
1231 */
1232 @Override
1233 public FileUploaderBinder getFileUploaderBinder() {
1234 return mUploaderBinder;
1235 }
1236
1237
1238 /** Defines callbacks for service binding, passed to bindService() */
1239 private class ListServiceConnection implements ServiceConnection {
1240
1241 @Override
1242 public void onServiceConnected(ComponentName component, IBinder service) {
1243 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1244 Log_OC.d(TAG, "Download service connected");
1245 mDownloaderBinder = (FileDownloaderBinder) service;
1246 if (mWaitingToPreview != null) {
1247 requestForDownload();
1248 }
1249
1250 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1251 Log_OC.d(TAG, "Upload service connected");
1252 mUploaderBinder = (FileUploaderBinder) service;
1253 } else {
1254 return;
1255 }
1256 // a new chance to get the mDownloadBinder through getFileDownloadBinder() - THIS IS A MESS
1257 OCFileListFragment listOfFiles = getListOfFilesFragment();
1258 if (listOfFiles != null) {
1259 listOfFiles.listDirectory();
1260 }
1261 FileFragment secondFragment = getSecondFragment();
1262 if (secondFragment != null && secondFragment instanceof FileDetailFragment) {
1263 FileDetailFragment detailFragment = (FileDetailFragment)secondFragment;
1264 detailFragment.listenForTransferProgress();
1265 detailFragment.updateFileDetails(false, false);
1266 }
1267 }
1268
1269 @Override
1270 public void onServiceDisconnected(ComponentName component) {
1271 if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloader.class))) {
1272 Log_OC.d(TAG, "Download service disconnected");
1273 mDownloaderBinder = null;
1274 } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
1275 Log_OC.d(TAG, "Upload service disconnected");
1276 mUploaderBinder = null;
1277 }
1278 }
1279 };
1280
1281
1282
1283 /**
1284 * Launch an intent to request the PIN code to the user before letting him use the app
1285 */
1286 private void requestPinCode() {
1287 boolean pinStart = false;
1288 SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
1289 pinStart = appPrefs.getBoolean("set_pincode", false);
1290 if (pinStart) {
1291 Intent i = new Intent(getApplicationContext(), PinCodeActivity.class);
1292 i.putExtra(PinCodeActivity.EXTRA_ACTIVITY, "FileDisplayActivity");
1293 startActivity(i);
1294 }
1295 }
1296
1297
1298 @Override
1299 public void onSavedCertificate() {
1300 startSyncFolderOperation(getCurrentDir());
1301 }
1302
1303
1304 @Override
1305 public void onFailedSavingCertificate() {
1306 showDialog(DIALOG_CERT_NOT_SAVED);
1307 }
1308
1309
1310 /**
1311 * Updates the view associated to the activity after the finish of some operation over files
1312 * in the current account.
1313 *
1314 * @param operation Removal operation performed.
1315 * @param result Result of the removal.
1316 */
1317 @Override
1318 public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
1319 super.onRemoteOperationFinish(operation, result);
1320
1321 if (operation instanceof RemoveFileOperation) {
1322 onRemoveFileOperationFinish((RemoveFileOperation)operation, result);
1323
1324 } else if (operation instanceof RenameFileOperation) {
1325 onRenameFileOperationFinish((RenameFileOperation)operation, result);
1326
1327 } else if (operation instanceof SynchronizeFileOperation) {
1328 onSynchronizeFileOperationFinish((SynchronizeFileOperation)operation, result);
1329
1330 } else if (operation instanceof CreateFolderOperation) {
1331 onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
1332
1333 } else if (operation instanceof CreateShareOperation) {
1334 onCreateShareOperationFinish((CreateShareOperation) operation, result);
1335
1336 } else if (operation instanceof UnshareLinkOperation) {
1337 onUnshareLinkOperationFinish((UnshareLinkOperation)operation, result);
1338
1339 }
1340
1341 }
1342
1343
1344 private void onCreateShareOperationFinish(CreateShareOperation operation, RemoteOperationResult result) {
1345 if (result.isSuccess()) {
1346 refreshShowDetails();
1347 refeshListOfFilesFragment();
1348 }
1349 }
1350
1351
1352 private void onUnshareLinkOperationFinish(UnshareLinkOperation operation, RemoteOperationResult result) {
1353 if (result.isSuccess() || result.getCode() == ResultCode.SHARE_NOT_FOUND) {
1354 refreshShowDetails();
1355 refeshListOfFilesFragment();
1356 }
1357 }
1358
1359 private void refreshShowDetails() {
1360 FileFragment details = getSecondFragment();
1361 if (details != null) {
1362 OCFile file = details.getFile();
1363 if (file != null) {
1364 file = getStorageManager().getFileByPath(file.getRemotePath()); {
1365 if (!(details instanceof PreviewMediaFragment || details instanceof PreviewImageFragment)) {
1366 showDetails(file);
1367 } else if (details instanceof PreviewMediaFragment) {
1368 startMediaPreview(file, 0, false);
1369 }
1370 }
1371 invalidateOptionsMenu();
1372 }
1373 }
1374 }
1375
1376 /**
1377 * Updates the view associated to the activity after the finish of an operation trying to remove a
1378 * file.
1379 *
1380 * @param operation Removal operation performed.
1381 * @param result Result of the removal.
1382 */
1383 private void onRemoveFileOperationFinish(RemoveFileOperation operation, RemoteOperationResult result) {
1384 dismissLoadingDialog();
1385 if (result.isSuccess()) {
1386 Toast msg = Toast.makeText(this, R.string.remove_success_msg, Toast.LENGTH_LONG);
1387 msg.show();
1388 OCFile removedFile = operation.getFile();
1389 getSecondFragment();
1390 FileFragment second = getSecondFragment();
1391 if (second != null && removedFile.equals(second.getFile())) {
1392 cleanSecondFragment();
1393 }
1394 if (getStorageManager().getFileById(removedFile.getParentId()).equals(getCurrentDir())) {
1395 refeshListOfFilesFragment();
1396 }
1397
1398 } else {
1399 Toast msg = Toast.makeText(this, R.string.remove_fail_msg, Toast.LENGTH_LONG);
1400 msg.show();
1401 if (result.isSslRecoverableException()) {
1402 mLastSslUntrustedServerResult = result;
1403 showDialog(DIALOG_SSL_VALIDATOR);
1404 }
1405 }
1406 }
1407
1408 /**
1409 * Updates the view associated to the activity after the finish of an operation trying create a new folder
1410 *
1411 * @param operation Creation operation performed.
1412 * @param result Result of the creation.
1413 */
1414 private void onCreateFolderOperationFinish(CreateFolderOperation operation, RemoteOperationResult result) {
1415 if (result.isSuccess()) {
1416 dismissLoadingDialog();
1417 refeshListOfFilesFragment();
1418
1419 } else {
1420 dismissLoadingDialog();
1421 if (result.getCode() == ResultCode.INVALID_CHARACTER_IN_NAME) {
1422 Toast.makeText(FileDisplayActivity.this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG).show();
1423 } else {
1424 try {
1425 Toast msg = Toast.makeText(FileDisplayActivity.this, R.string.create_dir_fail_msg, Toast.LENGTH_LONG);
1426 msg.show();
1427
1428 } catch (NotFoundException e) {
1429 Log_OC.e(TAG, "Error while trying to show fail message " , e);
1430 }
1431 }
1432 }
1433 }
1434
1435
1436 /**
1437 * Updates the view associated to the activity after the finish of an operation trying to rename a
1438 * file.
1439 *
1440 * @param operation Renaming operation performed.
1441 * @param result Result of the renaming.
1442 */
1443 private void onRenameFileOperationFinish(RenameFileOperation operation, RemoteOperationResult result) {
1444 dismissLoadingDialog();
1445 OCFile renamedFile = operation.getFile();
1446 if (result.isSuccess()) {
1447 if (mDualPane) {
1448 FileFragment details = getSecondFragment();
1449 if (details != null && details instanceof FileDetailFragment && renamedFile.equals(details.getFile()) ) {
1450 ((FileDetailFragment) details).updateFileDetails(renamedFile, getAccount());
1451 }
1452 }
1453 if (getStorageManager().getFileById(renamedFile.getParentId()).equals(getCurrentDir())) {
1454 refeshListOfFilesFragment();
1455 }
1456
1457 } else {
1458 if (result.getCode().equals(ResultCode.INVALID_LOCAL_FILE_NAME)) {
1459 Toast msg = Toast.makeText(this, R.string.rename_local_fail_msg, Toast.LENGTH_LONG);
1460 msg.show();
1461 // TODO throw again the new rename dialog
1462 } if (result.getCode().equals(ResultCode.INVALID_CHARACTER_IN_NAME)) {
1463 Toast msg = Toast.makeText(this, R.string.filename_forbidden_characters, Toast.LENGTH_LONG);
1464 msg.show();
1465 } else {
1466 Toast msg = Toast.makeText(this, R.string.rename_server_fail_msg, Toast.LENGTH_LONG);
1467 msg.show();
1468 if (result.isSslRecoverableException()) {
1469 mLastSslUntrustedServerResult = result;
1470 showDialog(DIALOG_SSL_VALIDATOR);
1471 }
1472 }
1473 }
1474 }
1475
1476
1477 private void onSynchronizeFileOperationFinish(SynchronizeFileOperation operation, RemoteOperationResult result) {
1478 dismissLoadingDialog();
1479 OCFile syncedFile = operation.getLocalFile();
1480 if (!result.isSuccess()) {
1481 if (result.getCode() == ResultCode.SYNC_CONFLICT) {
1482 Intent i = new Intent(this, ConflictsResolveActivity.class);
1483 i.putExtra(ConflictsResolveActivity.EXTRA_FILE, syncedFile);
1484 i.putExtra(ConflictsResolveActivity.EXTRA_ACCOUNT, getAccount());
1485 startActivity(i);
1486
1487 }
1488
1489 } else {
1490 if (operation.transferWasRequested()) {
1491 refeshListOfFilesFragment();
1492 onTransferStateChanged(syncedFile, true, true);
1493
1494 } else {
1495 Toast msg = Toast.makeText(this, R.string.sync_file_nothing_to_do_msg, Toast.LENGTH_LONG);
1496 msg.show();
1497 }
1498 }
1499 }
1500
1501
1502 /**
1503 * {@inheritDoc}
1504 */
1505 @Override
1506 public void onTransferStateChanged(OCFile file, boolean downloading, boolean uploading) {
1507 if (mDualPane) {
1508 FileFragment details = getSecondFragment();
1509 if (details != null && details instanceof FileDetailFragment && file.equals(details.getFile()) ) {
1510 if (downloading || uploading) {
1511 ((FileDetailFragment)details).updateFileDetails(file, getAccount());
1512 } else {
1513 ((FileDetailFragment)details).updateFileDetails(false, true);
1514 }
1515 }
1516 }
1517 }
1518
1519
1520 public void onDismiss(EditNameDialog dialog) {
1521 if (dialog.getResult()) {
1522 String newDirectoryName = dialog.getNewFilename().trim();
1523 Log_OC.d(TAG, "'create directory' dialog dismissed with new name " + newDirectoryName);
1524 if (newDirectoryName.length() > 0) {
1525 String path = getCurrentDir().getRemotePath();
1526
1527 // Create directory
1528 path += newDirectoryName + OCFile.PATH_SEPARATOR;
1529 RemoteOperation operation = new CreateFolderOperation(path, false, getStorageManager());
1530 operation.execute( getAccount(),
1531 FileDisplayActivity.this,
1532 FileDisplayActivity.this,
1533 getHandler(),
1534 FileDisplayActivity.this);
1535
1536 showLoadingDialog();
1537 }
1538 }
1539 }
1540
1541
1542 private void requestForDownload() {
1543 Account account = getAccount();
1544 if (!mDownloaderBinder.isDownloading(account, mWaitingToPreview)) {
1545 Intent i = new Intent(this, FileDownloader.class);
1546 i.putExtra(FileDownloader.EXTRA_ACCOUNT, account);
1547 i.putExtra(FileDownloader.EXTRA_FILE, mWaitingToPreview);
1548 startService(i);
1549 }
1550 }
1551
1552
1553 private OCFile getCurrentDir() {
1554 OCFile file = getFile();
1555 if (file != null) {
1556 if (file.isFolder()) {
1557 return file;
1558 } else if (getStorageManager() != null) {
1559 String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName()));
1560 return getStorageManager().getFileByPath(parentPath);
1561 }
1562 }
1563 return null;
1564 }
1565
1566 public void startSyncFolderOperation(OCFile folder) {
1567 long currentSyncTime = System.currentTimeMillis();
1568
1569 mSyncInProgress = true;
1570
1571 // perform folder synchronization
1572 RemoteOperation synchFolderOp = new SynchronizeFolderOperation( folder,
1573 currentSyncTime,
1574 false,
1575 getFileOperationsHelper().isSharedSupported(this),
1576 getStorageManager(),
1577 getAccount(),
1578 getApplicationContext()
1579 );
1580 synchFolderOp.execute(getAccount(), this, null, null, this);
1581
1582 setSupportProgressBarIndeterminateVisibility(true);
1583 }
1584
1585 /*
1586 private void startGetShares() {
1587 // Get shared files/folders
1588 Intent intent = new Intent(this, OperationsService.class);
1589 intent.putExtra(OperationsService.EXTRA_ACCOUNT, getAccount());
1590 startService(intent);
1591
1592 mRefreshSharesInProgress = true;
1593 }
1594 */
1595
1596 }