ReceiveExternalFilesActivity.java 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author masensio
  6. * @author Juan Carlos González Cabrero
  7. * @author David A. Velasco
  8. * Copyright (C) 2012 Bartek Przybylski
  9. * Copyright (C) 2016 ownCloud Inc.
  10. *
  11. * This program is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU General Public License version 2,
  13. * as published by the Free Software Foundation.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. */
  23. package com.owncloud.android.ui.activity;
  24. import android.accounts.Account;
  25. import android.accounts.AccountManager;
  26. import android.accounts.AuthenticatorException;
  27. import android.annotation.SuppressLint;
  28. import android.app.Dialog;
  29. import android.content.BroadcastReceiver;
  30. import android.content.Context;
  31. import android.content.DialogInterface;
  32. import android.content.IntentFilter;
  33. import android.content.DialogInterface.OnCancelListener;
  34. import android.content.DialogInterface.OnClickListener;
  35. import android.content.Intent;
  36. import android.content.res.Resources.NotFoundException;
  37. import android.os.Bundle;
  38. import android.os.Parcelable;
  39. import android.support.v4.app.FragmentManager;
  40. import android.support.v7.app.ActionBar;
  41. import android.support.v7.app.AlertDialog;
  42. import android.support.v7.app.AlertDialog.Builder;
  43. import android.view.Menu;
  44. import android.view.MenuInflater;
  45. import android.view.MenuItem;
  46. import android.view.View;
  47. import android.widget.AdapterView;
  48. import android.widget.AdapterView.OnItemClickListener;
  49. import android.widget.Button;
  50. import android.widget.ListView;
  51. import android.widget.Toast;
  52. import com.owncloud.android.MainApp;
  53. import com.owncloud.android.R;
  54. import com.owncloud.android.authentication.AccountAuthenticator;
  55. import com.owncloud.android.datamodel.OCFile;
  56. import com.owncloud.android.db.PreferenceManager;
  57. import com.owncloud.android.files.services.FileUploader;
  58. import com.owncloud.android.lib.common.operations.RemoteOperation;
  59. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  60. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  61. import com.owncloud.android.lib.common.utils.Log_OC;
  62. import com.owncloud.android.operations.CreateFolderOperation;
  63. import com.owncloud.android.operations.RefreshFolderOperation;
  64. import com.owncloud.android.syncadapter.FileSyncAdapter;
  65. import com.owncloud.android.ui.adapter.UploaderAdapter;
  66. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
  67. import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
  68. import com.owncloud.android.ui.asynctasks.CopyAndUploadContentUrisTask;
  69. import com.owncloud.android.ui.fragment.TaskRetainerFragment;
  70. import com.owncloud.android.ui.helpers.UriUploader;
  71. import com.owncloud.android.utils.DisplayUtils;
  72. import com.owncloud.android.utils.ErrorMessageAdapter;
  73. import com.owncloud.android.utils.FileStorageUtils;
  74. import java.util.ArrayList;
  75. import java.util.HashMap;
  76. import java.util.LinkedList;
  77. import java.util.List;
  78. import java.util.Stack;
  79. import java.util.Vector;
  80. /**
  81. * This can be used to upload things to an ownCloud instance.
  82. */
  83. public class ReceiveExternalFilesActivity extends FileActivity
  84. implements OnItemClickListener, android.view.View.OnClickListener,
  85. CopyAndUploadContentUrisTask.OnCopyTmpFilesTaskListener {
  86. private static final String TAG = ReceiveExternalFilesActivity.class.getSimpleName();
  87. private static final String FTAG_ERROR_FRAGMENT = "ERROR_FRAGMENT";
  88. private AccountManager mAccountManager;
  89. private Stack<String> mParents;
  90. private ArrayList<Parcelable> mStreamsToUpload;
  91. private String mUploadPath;
  92. private OCFile mFile;
  93. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  94. private boolean mSyncInProgress = false;
  95. private boolean mAccountSelected;
  96. private boolean mAccountSelectionShowing;
  97. private final static int DIALOG_NO_ACCOUNT = 0;
  98. private final static int DIALOG_MULTIPLE_ACCOUNT = 1;
  99. private final static int REQUEST_CODE__SETUP_ACCOUNT = REQUEST_CODE__LAST_SHARED + 1;
  100. private final static String KEY_PARENTS = "PARENTS";
  101. private final static String KEY_FILE = "FILE";
  102. private final static String KEY_ACCOUNT_SELECTED = "ACCOUNT_SELECTED";
  103. private final static String KEY_ACCOUNT_SELECTION_SHOWING = "ACCOUNT_SELECTION_SHOWING";
  104. private static final String DIALOG_WAIT_COPY_FILE = "DIALOG_WAIT_COPY_FILE";
  105. @Override
  106. protected void onCreate(Bundle savedInstanceState) {
  107. prepareStreamsToUpload();
  108. if (savedInstanceState == null) {
  109. mParents = new Stack<>();
  110. mAccountSelected = false;
  111. mAccountSelectionShowing = false;
  112. } else {
  113. mParents = (Stack<String>) savedInstanceState.getSerializable(KEY_PARENTS);
  114. mFile = savedInstanceState.getParcelable(KEY_FILE);
  115. mAccountSelected = savedInstanceState.getBoolean(KEY_ACCOUNT_SELECTED);
  116. mAccountSelectionShowing = savedInstanceState.getBoolean(KEY_ACCOUNT_SELECTION_SHOWING);
  117. }
  118. super.onCreate(savedInstanceState);
  119. if (mAccountSelected) {
  120. setAccount((Account) savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT));
  121. }
  122. // Listen for sync messages
  123. IntentFilter syncIntentFilter = new IntentFilter(RefreshFolderOperation.
  124. EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  125. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  126. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  127. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  128. // Init Fragment without UI to retain AsyncTask across configuration changes
  129. FragmentManager fm = getSupportFragmentManager();
  130. TaskRetainerFragment taskRetainerFragment =
  131. (TaskRetainerFragment) fm.findFragmentByTag(TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT);
  132. if (taskRetainerFragment == null) {
  133. taskRetainerFragment = new TaskRetainerFragment();
  134. fm.beginTransaction()
  135. .add(taskRetainerFragment, TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT).commit();
  136. } // else, Fragment already created and retained across configuration change
  137. }
  138. @Override
  139. protected void setAccount(Account account, boolean savedAccount) {
  140. if (somethingToUpload()) {
  141. mAccountManager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
  142. Account[] accounts = mAccountManager.getAccountsByType(MainApp.getAccountType());
  143. if (accounts.length == 0) {
  144. Log_OC.i(TAG, "No ownCloud account is available");
  145. showDialog(DIALOG_NO_ACCOUNT);
  146. } else if (accounts.length > 1 && !mAccountSelected && !mAccountSelectionShowing) {
  147. Log_OC.i(TAG, "More than one ownCloud is available");
  148. showDialog(DIALOG_MULTIPLE_ACCOUNT);
  149. mAccountSelectionShowing = true;
  150. } else {
  151. if (!savedAccount) {
  152. setAccount(accounts[0]);
  153. }
  154. }
  155. } else if (getIntent().getStringExtra(Intent.EXTRA_TEXT) != null) {
  156. showErrorDialog(
  157. R.string.uploader_error_message_received_piece_of_text,
  158. R.string.uploader_error_title_no_file_to_upload
  159. );
  160. } else {
  161. showErrorDialog(
  162. R.string.uploader_error_message_no_file_to_upload,
  163. R.string.uploader_error_title_no_file_to_upload
  164. );
  165. }
  166. super.setAccount(account, savedAccount);
  167. }
  168. @Override
  169. protected void onAccountSet(boolean stateWasRecovered) {
  170. super.onAccountSet(mAccountWasRestored);
  171. initTargetFolder();
  172. populateDirectoryList();
  173. }
  174. @Override
  175. protected void onSaveInstanceState(Bundle outState) {
  176. Log_OC.d(TAG, "onSaveInstanceState() start");
  177. super.onSaveInstanceState(outState);
  178. outState.putSerializable(KEY_PARENTS, mParents);
  179. //outState.putParcelable(KEY_ACCOUNT, mAccount);
  180. outState.putParcelable(KEY_FILE, mFile);
  181. outState.putBoolean(KEY_ACCOUNT_SELECTED, mAccountSelected);
  182. outState.putBoolean(KEY_ACCOUNT_SELECTION_SHOWING, mAccountSelectionShowing);
  183. outState.putParcelable(FileActivity.EXTRA_ACCOUNT, getAccount());
  184. Log_OC.d(TAG, "onSaveInstanceState() end");
  185. }
  186. @Override
  187. protected void onDestroy(){
  188. if (mSyncBroadcastReceiver != null) {
  189. unregisterReceiver(mSyncBroadcastReceiver);
  190. }
  191. super.onDestroy();
  192. }
  193. @Override
  194. protected Dialog onCreateDialog(final int id) {
  195. final AlertDialog.Builder builder = new Builder(this);
  196. switch (id) {
  197. case DIALOG_NO_ACCOUNT:
  198. builder.setIcon(R.drawable.ic_warning);
  199. builder.setTitle(R.string.uploader_wrn_no_account_title);
  200. builder.setMessage(String.format(
  201. getString(R.string.uploader_wrn_no_account_text),
  202. getString(R.string.app_name)));
  203. builder.setCancelable(false);
  204. builder.setPositiveButton(R.string.uploader_wrn_no_account_setup_btn_text, new OnClickListener() {
  205. @Override
  206. public void onClick(DialogInterface dialog, int which) {
  207. if (android.os.Build.VERSION.SDK_INT >
  208. android.os.Build.VERSION_CODES.ECLAIR_MR1) {
  209. // using string value since in API7 this
  210. // constatn is not defined
  211. // in API7 < this constatant is defined in
  212. // Settings.ADD_ACCOUNT_SETTINGS
  213. // and Settings.EXTRA_AUTHORITIES
  214. Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
  215. intent.putExtra("authorities", new String[]{MainApp.getAuthTokenType()});
  216. startActivityForResult(intent, REQUEST_CODE__SETUP_ACCOUNT);
  217. } else {
  218. // since in API7 there is no direct call for
  219. // account setup, so we need to
  220. // show our own AccountSetupAcricity, get
  221. // desired results and setup
  222. // everything for ourself
  223. Intent intent = new Intent(getBaseContext(), AccountAuthenticator.class);
  224. startActivityForResult(intent, REQUEST_CODE__SETUP_ACCOUNT);
  225. }
  226. }
  227. });
  228. builder.setNegativeButton(R.string.uploader_wrn_no_account_quit_btn_text, new OnClickListener() {
  229. @Override
  230. public void onClick(DialogInterface dialog, int which) {
  231. finish();
  232. }
  233. });
  234. return builder.create();
  235. case DIALOG_MULTIPLE_ACCOUNT:
  236. CharSequence ac[] = new CharSequence[
  237. mAccountManager.getAccountsByType(MainApp.getAccountType()).length];
  238. for (int i = 0; i < ac.length; ++i) {
  239. ac[i] = DisplayUtils.convertIdn(
  240. mAccountManager.getAccountsByType(MainApp.getAccountType())[i].name, false);
  241. }
  242. builder.setTitle(R.string.common_choose_account);
  243. builder.setItems(ac, new OnClickListener() {
  244. @Override
  245. public void onClick(DialogInterface dialog, int which) {
  246. setAccount(mAccountManager.getAccountsByType(MainApp.getAccountType())[which]);
  247. onAccountSet(mAccountWasRestored);
  248. dialog.dismiss();
  249. mAccountSelected = true;
  250. mAccountSelectionShowing = false;
  251. }
  252. });
  253. builder.setCancelable(true);
  254. builder.setOnCancelListener(new OnCancelListener() {
  255. @Override
  256. public void onCancel(DialogInterface dialog) {
  257. mAccountSelectionShowing = false;
  258. dialog.cancel();
  259. finish();
  260. }
  261. });
  262. return builder.create();
  263. default:
  264. throw new IllegalArgumentException("Unknown dialog id: " + id);
  265. }
  266. }
  267. @Override
  268. public void onBackPressed() {
  269. if (mParents.size() <= 1) {
  270. super.onBackPressed();
  271. } else {
  272. mParents.pop();
  273. String full_path = generatePath(mParents);
  274. startSyncFolderOperation(getStorageManager().getFileByPath(full_path));
  275. populateDirectoryList();
  276. }
  277. }
  278. @Override
  279. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  280. // click on folder in the list
  281. Log_OC.d(TAG, "on item click");
  282. // TODO Enable when "On Device" is recovered ?
  283. Vector<OCFile> tmpfiles = getStorageManager().getFolderContent(mFile /*, false*/);
  284. tmpfiles = sortFileList(tmpfiles);
  285. if (tmpfiles.size() <= 0) return;
  286. // filter on dirtype
  287. Vector<OCFile> files = new Vector<>();
  288. for (OCFile f : tmpfiles)
  289. files.add(f);
  290. if (files.size() < position) {
  291. throw new IndexOutOfBoundsException("Incorrect item selected");
  292. }
  293. if (files.get(position).isFolder()){
  294. OCFile folderToEnter = files.get(position);
  295. startSyncFolderOperation(folderToEnter);
  296. mParents.push(folderToEnter.getFileName());
  297. populateDirectoryList();
  298. }
  299. }
  300. @Override
  301. public void onClick(View v) {
  302. // click on button
  303. switch (v.getId()) {
  304. case R.id.uploader_choose_folder:
  305. mUploadPath = ""; // first element in mParents is root dir, represented by "";
  306. // init mUploadPath with "/" results in a "//" prefix
  307. for (String p : mParents) {
  308. mUploadPath += p + OCFile.PATH_SEPARATOR;
  309. }
  310. Log_OC.d(TAG, "Uploading file to dir " + mUploadPath);
  311. uploadFiles();
  312. break;
  313. case R.id.uploader_cancel:
  314. finish();
  315. break;
  316. default:
  317. throw new IllegalArgumentException("Wrong element clicked");
  318. }
  319. }
  320. @Override
  321. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  322. super.onActivityResult(requestCode, resultCode, data);
  323. Log_OC.i(TAG, "result received. req: " + requestCode + " res: " + resultCode);
  324. if (requestCode == REQUEST_CODE__SETUP_ACCOUNT) {
  325. dismissDialog(DIALOG_NO_ACCOUNT);
  326. if (resultCode == RESULT_CANCELED) {
  327. finish();
  328. }
  329. Account[] accounts = mAccountManager.getAccountsByType(MainApp.getAuthTokenType());
  330. if (accounts.length == 0) {
  331. showDialog(DIALOG_NO_ACCOUNT);
  332. } else {
  333. // there is no need for checking for is there more then one
  334. // account at this point
  335. // since account setup can set only one account at time
  336. setAccount(accounts[0]);
  337. populateDirectoryList();
  338. }
  339. }
  340. }
  341. private void populateDirectoryList() {
  342. setContentView(R.layout.uploader_layout);
  343. ListView mListView = (ListView) findViewById(android.R.id.list);
  344. ActionBar actionBar = getSupportActionBar();
  345. String current_dir = mParents.peek();
  346. if (current_dir.equals("")) {
  347. actionBar.setTitle(getString(R.string.uploader_top_message));
  348. } else {
  349. actionBar.setTitle(current_dir);
  350. }
  351. boolean notRoot = (mParents.size() > 1);
  352. actionBar.setDisplayHomeAsUpEnabled(notRoot);
  353. actionBar.setHomeButtonEnabled(notRoot);
  354. String full_path = generatePath(mParents);
  355. Log_OC.d(TAG, "Populating view with content of : " + full_path);
  356. mFile = getStorageManager().getFileByPath(full_path);
  357. if (mFile != null) {
  358. // TODO Enable when "On Device" is recovered ?
  359. Vector<OCFile> files = getStorageManager().getFolderContent(mFile/*, false*/);
  360. files = sortFileList(files);
  361. List<HashMap<String, Object>> data = new LinkedList<>();
  362. for (OCFile f : files) {
  363. if (f.isFolder()) {
  364. HashMap<String, Object> h = new HashMap<>();
  365. h.put("dirname", f);
  366. data.add(h);
  367. }
  368. }
  369. UploaderAdapter sa = new UploaderAdapter(this,
  370. data,
  371. R.layout.uploader_list_item_layout,
  372. new String[] {"dirname"},
  373. new int[] {R.id.filename},
  374. getStorageManager(), getAccount());
  375. mListView.setAdapter(sa);
  376. Button btnChooseFolder = (Button) findViewById(R.id.uploader_choose_folder);
  377. btnChooseFolder.setOnClickListener(this);
  378. Button btnNewFolder = (Button) findViewById(R.id.uploader_cancel);
  379. btnNewFolder.setOnClickListener(this);
  380. mListView.setOnItemClickListener(this);
  381. }
  382. }
  383. @Override
  384. public void onSavedCertificate() {
  385. startSyncFolderOperation(getCurrentDir());
  386. }
  387. private void startSyncFolderOperation(OCFile folder) {
  388. long currentSyncTime = System.currentTimeMillis();
  389. mSyncInProgress = true;
  390. // perform folder synchronization
  391. RemoteOperation synchFolderOp = new RefreshFolderOperation( folder,
  392. currentSyncTime,
  393. false,
  394. false,
  395. false,
  396. getStorageManager(),
  397. getAccount(),
  398. getApplicationContext()
  399. );
  400. synchFolderOp.execute(getAccount(), this, null, null);
  401. }
  402. private Vector<OCFile> sortFileList(Vector<OCFile> files) {
  403. SharedPreferences sharedPreferences = PreferenceManager
  404. .getDefaultSharedPreferences(this);
  405. // Read sorting order, default to sort by name ascending
  406. FileStorageUtils.mSortOrder = sharedPreferences.getInt("sortOrder", 0);
  407. FileStorageUtils.mSortAscending = sharedPreferences.getBoolean("sortAscending", true);
  408. files = FileStorageUtils.sortFolder(files);
  409. return files;
  410. }
  411. private String generatePath(Stack<String> dirs) {
  412. String full_path = "";
  413. for (String a : dirs)
  414. full_path += a + "/";
  415. return full_path;
  416. }
  417. private void prepareStreamsToUpload() {
  418. if (getIntent().getAction().equals(Intent.ACTION_SEND)) {
  419. mStreamsToUpload = new ArrayList<>();
  420. mStreamsToUpload.add(getIntent().getParcelableExtra(Intent.EXTRA_STREAM));
  421. } else if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
  422. mStreamsToUpload = getIntent().getParcelableArrayListExtra(Intent.EXTRA_STREAM);
  423. }
  424. }
  425. private boolean somethingToUpload() {
  426. return (mStreamsToUpload != null && mStreamsToUpload.get(0) != null);
  427. }
  428. @SuppressLint("NewApi")
  429. public void uploadFiles() {
  430. UriUploader uploader = new UriUploader(
  431. this,
  432. mStreamsToUpload,
  433. mUploadPath,
  434. getAccount(),
  435. FileUploader.LOCAL_BEHAVIOUR_FORGET,
  436. true, // Show waiting dialog while file is being copied from private storage
  437. this // Copy temp task listener
  438. );
  439. UriUploader.UriUploaderResultCode resultCode = uploader.uploadUris();
  440. // Save the path to shared preferences; even if upload is not possible, user chose the folder
  441. PreferenceManager.setLastUploadPath(mUploadPath, this);
  442. if (resultCode == UriUploader.UriUploaderResultCode.OK) {
  443. finish();
  444. } else {
  445. int messageResTitle = R.string.uploader_error_title_file_cannot_be_uploaded;
  446. int messageResId = R.string.common_error_unknown;
  447. if (resultCode == UriUploader.UriUploaderResultCode.ERROR_NO_FILE_TO_UPLOAD) {
  448. messageResId = R.string.uploader_error_message_no_file_to_upload;
  449. messageResTitle = R.string.uploader_error_title_no_file_to_upload;
  450. } else if (resultCode == UriUploader.UriUploaderResultCode.ERROR_READ_PERMISSION_NOT_GRANTED) {
  451. messageResId = R.string.uploader_error_message_read_permission_not_granted;
  452. } else if (resultCode == UriUploader.UriUploaderResultCode.ERROR_UNKNOWN) {
  453. messageResId = R.string.common_error_unknown;
  454. }
  455. showErrorDialog(
  456. messageResId,
  457. messageResTitle
  458. );
  459. }
  460. }
  461. @Override
  462. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  463. super.onRemoteOperationFinish(operation, result);
  464. if (operation instanceof CreateFolderOperation) {
  465. onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
  466. }
  467. }
  468. /**
  469. * Updates the view associated to the activity after the finish of an operation
  470. * trying create a new folder
  471. *
  472. * @param operation Creation operation performed.
  473. * @param result Result of the creation.
  474. */
  475. private void onCreateFolderOperationFinish(CreateFolderOperation operation,
  476. RemoteOperationResult result) {
  477. if (result.isSuccess()) {
  478. populateDirectoryList();
  479. } else {
  480. try {
  481. Toast msg = Toast.makeText(this,
  482. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  483. Toast.LENGTH_LONG);
  484. msg.show();
  485. } catch (NotFoundException e) {
  486. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  487. }
  488. }
  489. }
  490. /**
  491. * Loads the target folder initialize shown to the user.
  492. * <p/>
  493. * The target account has to be chosen before this method is called.
  494. */
  495. private void initTargetFolder() {
  496. if (getStorageManager() == null) {
  497. throw new IllegalStateException("Do not call this method before " +
  498. "initializing mStorageManager");
  499. }
  500. String lastPath = PreferenceManager.getLastUploadPath(this);
  501. // "/" equals root-directory
  502. if (lastPath.equals("/")) {
  503. mParents.add("");
  504. } else {
  505. String[] dir_names = lastPath.split("/");
  506. mParents.clear();
  507. for (String dir : dir_names)
  508. mParents.add(dir);
  509. }
  510. //Make sure that path still exists, if it doesn't pop the stack and try the previous path
  511. while (!getStorageManager().fileExists(generatePath(mParents)) && mParents.size() > 1) {
  512. mParents.pop();
  513. }
  514. }
  515. @Override
  516. public boolean onCreateOptionsMenu(Menu menu) {
  517. MenuInflater inflater = getMenuInflater();
  518. inflater.inflate(R.menu.main_menu, menu);
  519. menu.findItem(R.id.action_sort).setVisible(false);
  520. menu.findItem(R.id.action_switch_view).setVisible(false);
  521. menu.findItem(R.id.action_sync_account).setVisible(false);
  522. return true;
  523. }
  524. @Override
  525. public boolean onOptionsItemSelected(MenuItem item) {
  526. boolean retval = true;
  527. switch (item.getItemId()) {
  528. case R.id.action_create_dir:
  529. CreateFolderDialogFragment dialog = CreateFolderDialogFragment.newInstance(mFile);
  530. dialog.show(
  531. getSupportFragmentManager(),
  532. CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT);
  533. break;
  534. case android.R.id.home:
  535. if ((mParents.size() > 1)) {
  536. onBackPressed();
  537. }
  538. break;
  539. default:
  540. retval = super.onOptionsItemSelected(item);
  541. }
  542. return retval;
  543. }
  544. private OCFile getCurrentFolder(){
  545. OCFile file = mFile;
  546. if (file != null) {
  547. if (file.isFolder()) {
  548. return file;
  549. } else if (getStorageManager() != null) {
  550. return getStorageManager().getFileByPath(file.getParentRemotePath());
  551. }
  552. }
  553. return null;
  554. }
  555. private void browseToRoot() {
  556. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  557. mFile = root;
  558. startSyncFolderOperation(root);
  559. }
  560. private class SyncBroadcastReceiver extends BroadcastReceiver {
  561. /**
  562. * {@link BroadcastReceiver} to enable syncing feedback in UI
  563. */
  564. @Override
  565. public void onReceive(Context context, Intent intent) {
  566. try {
  567. String event = intent.getAction();
  568. Log_OC.d(TAG, "Received broadcast " + event);
  569. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  570. String synchFolderRemotePath =
  571. intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  572. RemoteOperationResult synchResult =
  573. (RemoteOperationResult) intent.getSerializableExtra(
  574. FileSyncAdapter.EXTRA_RESULT);
  575. boolean sameAccount = (getAccount() != null &&
  576. accountName.equals(getAccount().name) && getStorageManager() != null);
  577. if (sameAccount) {
  578. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  579. mSyncInProgress = true;
  580. } else {
  581. OCFile currentFile = (mFile == null) ? null :
  582. getStorageManager().getFileByPath(mFile.getRemotePath());
  583. OCFile currentDir = (getCurrentFolder() == null) ? null :
  584. getStorageManager().getFileByPath(getCurrentFolder().getRemotePath());
  585. if (currentDir == null) {
  586. // current folder was removed from the server
  587. Toast.makeText(context,
  588. String.format(
  589. getString(R.string.sync_current_folder_was_removed),
  590. getCurrentFolder().getFileName()),
  591. Toast.LENGTH_LONG)
  592. .show();
  593. browseToRoot();
  594. } else {
  595. if (currentFile == null && !mFile.isFolder()) {
  596. // currently selected file was removed in the server, and now we know it
  597. currentFile = currentDir;
  598. }
  599. if (synchFolderRemotePath != null &&
  600. currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  601. populateDirectoryList();
  602. }
  603. mFile = currentFile;
  604. }
  605. mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
  606. !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
  607. if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
  608. equals(event) &&
  609. /// TODO refactor and make common
  610. synchResult != null && !synchResult.isSuccess()) {
  611. if(synchResult.getCode() == ResultCode.UNAUTHORIZED ||
  612. (synchResult.isException() && synchResult.getException()
  613. instanceof AuthenticatorException)) {
  614. requestCredentialsUpdate(context);
  615. } else if(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(synchResult.getCode())) {
  616. showUntrustedCertDialog(synchResult);
  617. }
  618. }
  619. }
  620. removeStickyBroadcast(intent);
  621. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  622. }
  623. } catch (RuntimeException e) {
  624. // avoid app crashes after changing the serial id of RemoteOperationResult
  625. // in owncloud library with broadcast notifications pending to process
  626. removeStickyBroadcast(intent);
  627. }
  628. }
  629. }
  630. /**
  631. * Process the result of CopyAndUploadContentUrisTask
  632. */
  633. @Override
  634. public void onTmpFilesCopied(ResultCode result) {
  635. dismissLoadingDialog();
  636. finish();
  637. }
  638. /**
  639. * Show an error dialog, forcing the user to click a single button to exit the activity
  640. *
  641. * @param messageResId Resource id of the message to show in the dialog.
  642. * @param messageResTitle Resource id of the title to show in the dialog. 0 to show default alert message.
  643. * -1 to show no title.
  644. */
  645. private void showErrorDialog(int messageResId, int messageResTitle) {
  646. ConfirmationDialogFragment errorDialog = ConfirmationDialogFragment.newInstance(
  647. messageResId,
  648. new String[]{getString(R.string.app_name)}, // see uploader_error_message_* in strings.xml
  649. messageResTitle,
  650. R.string.common_back,
  651. -1,
  652. -1
  653. );
  654. errorDialog.setCancelable(false);
  655. errorDialog.setOnConfirmationListener(
  656. new ConfirmationDialogFragment.ConfirmationDialogFragmentListener() {
  657. @Override
  658. public void onConfirmation(String callerTag) {
  659. finish();
  660. }
  661. @Override
  662. public void onNeutral(String callerTag) {}
  663. @Override
  664. public void onCancel(String callerTag) {}
  665. }
  666. );
  667. errorDialog.show(getSupportFragmentManager(), FTAG_ERROR_FRAGMENT);
  668. }
  669. }