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