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