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