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