ReceiveExternalFilesActivity.java 34 KB

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