ReceiveExternalFilesActivity.java 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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.OnClickListener;
  33. import android.content.Intent;
  34. import android.content.IntentFilter;
  35. import android.content.res.Resources.NotFoundException;
  36. import android.os.Bundle;
  37. import android.os.Parcelable;
  38. import android.support.annotation.NonNull;
  39. import android.support.annotation.Nullable;
  40. import android.support.v4.app.DialogFragment;
  41. import android.support.v4.app.FragmentManager;
  42. import android.support.v7.app.ActionBar;
  43. import android.support.v7.app.AlertDialog;
  44. import android.support.v7.app.AlertDialog.Builder;
  45. import android.text.format.DateFormat;
  46. import android.view.LayoutInflater;
  47. import android.view.Menu;
  48. import android.view.MenuInflater;
  49. import android.view.MenuItem;
  50. import android.view.View;
  51. import android.view.WindowManager.LayoutParams;
  52. import android.widget.AdapterView;
  53. import android.widget.AdapterView.OnItemClickListener;
  54. import android.widget.ArrayAdapter;
  55. import android.widget.Button;
  56. import android.widget.EditText;
  57. import android.widget.ListView;
  58. import android.widget.Spinner;
  59. import android.widget.TextView;
  60. import android.widget.Toast;
  61. import com.owncloud.android.MainApp;
  62. import com.owncloud.android.R;
  63. import com.owncloud.android.authentication.AccountAuthenticator;
  64. import com.owncloud.android.datamodel.OCFile;
  65. import com.owncloud.android.db.PreferenceManager;
  66. import com.owncloud.android.files.services.FileUploader;
  67. import com.owncloud.android.lib.common.operations.RemoteOperation;
  68. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  69. import com.owncloud.android.lib.common.operations.RemoteOperationResult.ResultCode;
  70. import com.owncloud.android.lib.common.utils.Log_OC;
  71. import com.owncloud.android.operations.CreateFolderOperation;
  72. import com.owncloud.android.operations.RefreshFolderOperation;
  73. import com.owncloud.android.operations.UploadFileOperation;
  74. import com.owncloud.android.syncadapter.FileSyncAdapter;
  75. import com.owncloud.android.ui.adapter.UploaderAdapter;
  76. import com.owncloud.android.ui.asynctasks.CopyAndUploadContentUrisTask;
  77. import com.owncloud.android.ui.dialog.ConfirmationDialogFragment;
  78. import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
  79. import com.owncloud.android.ui.fragment.TaskRetainerFragment;
  80. import com.owncloud.android.ui.helpers.UriUploader;
  81. import com.owncloud.android.utils.DisplayUtils;
  82. import com.owncloud.android.utils.ErrorMessageAdapter;
  83. import com.owncloud.android.utils.FileStorageUtils;
  84. import java.io.File;
  85. import java.io.FileWriter;
  86. import java.io.IOException;
  87. import java.io.UnsupportedEncodingException;
  88. import java.lang.reflect.Method;
  89. import java.util.ArrayList;
  90. import java.util.Calendar;
  91. import java.util.HashMap;
  92. import java.util.LinkedList;
  93. import java.util.List;
  94. import java.util.Stack;
  95. import java.util.Vector;
  96. /**
  97. * This can be used to upload things to an ownCloud instance.
  98. */
  99. public class ReceiveExternalFilesActivity extends FileActivity
  100. implements OnItemClickListener, android.view.View.OnClickListener,
  101. CopyAndUploadContentUrisTask.OnCopyTmpFilesTaskListener {
  102. private static final String TAG = ReceiveExternalFilesActivity.class.getSimpleName();
  103. private static final String FTAG_ERROR_FRAGMENT = "ERROR_FRAGMENT";
  104. public static final String TEXT_FILE_SUFFIX = ".txt";
  105. public static final String URL_FILE_SUFFIX = ".url";
  106. public static final String WEBLOC_FILE_SUFFIX = ".webloc";
  107. public static final String DESKTOP_FILE_SUFFIX = ".desktop";
  108. private AccountManager mAccountManager;
  109. private Stack<String> mParents;
  110. private ArrayList<Parcelable> mStreamsToUpload;
  111. private String mUploadPath;
  112. private OCFile mFile;
  113. private SyncBroadcastReceiver mSyncBroadcastReceiver;
  114. private boolean mSyncInProgress = false;
  115. private boolean mAccountSelected;
  116. private boolean mAccountSelectionShowing;
  117. private final static int REQUEST_CODE__SETUP_ACCOUNT = REQUEST_CODE__LAST_SHARED + 1;
  118. private final static String KEY_PARENTS = "PARENTS";
  119. private final static String KEY_FILE = "FILE";
  120. private final static String KEY_ACCOUNT_SELECTED = "ACCOUNT_SELECTED";
  121. private final static String KEY_ACCOUNT_SELECTION_SHOWING = "ACCOUNT_SELECTION_SHOWING";
  122. private boolean mUploadFromTmpFile = false;
  123. private String mSubjectText;
  124. private String mExtraText;
  125. private final static String FILENAME_ENCODING = "UTF-8";
  126. @Override
  127. protected void onCreate(Bundle savedInstanceState) {
  128. prepareStreamsToUpload();
  129. if (savedInstanceState == null) {
  130. mParents = new Stack<>();
  131. mAccountSelected = false;
  132. mAccountSelectionShowing = false;
  133. } else {
  134. mParents = (Stack<String>) savedInstanceState.getSerializable(KEY_PARENTS);
  135. mFile = savedInstanceState.getParcelable(KEY_FILE);
  136. mAccountSelected = savedInstanceState.getBoolean(KEY_ACCOUNT_SELECTED);
  137. mAccountSelectionShowing = savedInstanceState.getBoolean(KEY_ACCOUNT_SELECTION_SHOWING);
  138. }
  139. super.onCreate(savedInstanceState);
  140. if (mAccountSelected) {
  141. setAccount((Account) savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT));
  142. }
  143. // Listen for sync messages
  144. IntentFilter syncIntentFilter = new IntentFilter(RefreshFolderOperation.
  145. EVENT_SINGLE_FOLDER_CONTENTS_SYNCED);
  146. syncIntentFilter.addAction(RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED);
  147. mSyncBroadcastReceiver = new SyncBroadcastReceiver();
  148. registerReceiver(mSyncBroadcastReceiver, syncIntentFilter);
  149. // Init Fragment without UI to retain AsyncTask across configuration changes
  150. FragmentManager fm = getSupportFragmentManager();
  151. TaskRetainerFragment taskRetainerFragment =
  152. (TaskRetainerFragment) fm.findFragmentByTag(TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT);
  153. if (taskRetainerFragment == null) {
  154. taskRetainerFragment = new TaskRetainerFragment();
  155. fm.beginTransaction()
  156. .add(taskRetainerFragment, TaskRetainerFragment.FTAG_TASK_RETAINER_FRAGMENT).commit();
  157. } // else, Fragment already created and retained across configuration change
  158. }
  159. @Override
  160. protected void setAccount(Account account, boolean savedAccount) {
  161. if (somethingToUpload()) {
  162. mAccountManager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
  163. Account[] accounts = mAccountManager.getAccountsByType(MainApp.getAccountType());
  164. if (accounts.length == 0) {
  165. Log_OC.i(TAG, "No ownCloud account is available");
  166. DialogNoAccount dialog = new DialogNoAccount();
  167. dialog.show(getSupportFragmentManager(), null);
  168. } else if (accounts.length > 1 && !mAccountSelected && !mAccountSelectionShowing) {
  169. Log_OC.i(TAG, "More than one ownCloud is available");
  170. DialogMultipleAccount dialog = new DialogMultipleAccount();
  171. dialog.show(getSupportFragmentManager(), null);
  172. mAccountSelectionShowing = true;
  173. } else {
  174. if (!savedAccount) {
  175. setAccount(accounts[0]);
  176. }
  177. }
  178. } else {
  179. showErrorDialog(
  180. R.string.uploader_error_message_no_file_to_upload,
  181. R.string.uploader_error_title_no_file_to_upload
  182. );
  183. }
  184. super.setAccount(account, savedAccount);
  185. }
  186. @Override
  187. protected void onAccountSet(boolean stateWasRecovered) {
  188. super.onAccountSet(mAccountWasRestored);
  189. initTargetFolder();
  190. populateDirectoryList();
  191. }
  192. @Override
  193. protected void onSaveInstanceState(Bundle outState) {
  194. Log_OC.d(TAG, "onSaveInstanceState() start");
  195. super.onSaveInstanceState(outState);
  196. outState.putSerializable(KEY_PARENTS, mParents);
  197. outState.putParcelable(KEY_FILE, mFile);
  198. outState.putBoolean(KEY_ACCOUNT_SELECTED, mAccountSelected);
  199. outState.putBoolean(KEY_ACCOUNT_SELECTION_SHOWING, mAccountSelectionShowing);
  200. outState.putParcelable(FileActivity.EXTRA_ACCOUNT, getAccount());
  201. Log_OC.d(TAG, "onSaveInstanceState() end");
  202. }
  203. @Override
  204. protected void onDestroy(){
  205. if (mSyncBroadcastReceiver != null) {
  206. unregisterReceiver(mSyncBroadcastReceiver);
  207. }
  208. super.onDestroy();
  209. }
  210. public static class DialogNoAccount extends DialogFragment {
  211. @Override
  212. public Dialog onCreateDialog(Bundle savedInstanceState) {
  213. AlertDialog.Builder builder = new Builder(getActivity());
  214. builder.setIcon(R.drawable.ic_warning);
  215. builder.setTitle(R.string.uploader_wrn_no_account_title);
  216. builder.setMessage(String.format(
  217. getString(R.string.uploader_wrn_no_account_text),
  218. getString(R.string.app_name)));
  219. builder.setCancelable(false);
  220. builder.setPositiveButton(R.string.uploader_wrn_no_account_setup_btn_text, new OnClickListener() {
  221. @Override
  222. public void onClick(DialogInterface dialog, int which) {
  223. if (android.os.Build.VERSION.SDK_INT >
  224. android.os.Build.VERSION_CODES.ECLAIR_MR1) {
  225. // using string value since in API7 this
  226. // constatn is not defined
  227. // in API7 < this constatant is defined in
  228. // Settings.ADD_ACCOUNT_SETTINGS
  229. // and Settings.EXTRA_AUTHORITIES
  230. Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
  231. intent.putExtra("authorities", new String[]{MainApp.getAuthTokenType()});
  232. startActivityForResult(intent, REQUEST_CODE__SETUP_ACCOUNT);
  233. } else {
  234. // since in API7 there is no direct call for
  235. // account setup, so we need to
  236. // show our own AccountSetupAcricity, get
  237. // desired results and setup
  238. // everything for ourself
  239. Intent intent = new Intent(getActivity().getBaseContext(), AccountAuthenticator.class);
  240. startActivityForResult(intent, REQUEST_CODE__SETUP_ACCOUNT);
  241. }
  242. }
  243. });
  244. builder.setNegativeButton(R.string.uploader_wrn_no_account_quit_btn_text, new OnClickListener() {
  245. @Override
  246. public void onClick(DialogInterface dialog, int which) {
  247. getActivity().finish();
  248. }
  249. });
  250. return builder.create();
  251. }
  252. }
  253. public static class DialogMultipleAccount extends DialogFragment {
  254. @NonNull
  255. @Override
  256. public Dialog onCreateDialog(Bundle savedInstanceState) {
  257. final ReceiveExternalFilesActivity parent = (ReceiveExternalFilesActivity) getActivity();
  258. AlertDialog.Builder builder = new Builder(parent);
  259. Account accounts[] = parent.mAccountManager.getAccountsByType(MainApp.getAccountType());
  260. CharSequence dialogItems[] = new CharSequence[accounts.length];
  261. for (int i = 0; i < dialogItems.length; ++i) {
  262. dialogItems[i] = DisplayUtils.getAccountNameDisplayText(
  263. parent, accounts[i], accounts[i].name, DisplayUtils.convertIdn(accounts[i].name, false));
  264. }
  265. builder.setTitle(R.string.common_choose_account);
  266. builder.setItems(dialogItems, new OnClickListener() {
  267. @Override
  268. public void onClick(DialogInterface dialog, int which) {
  269. final ReceiveExternalFilesActivity parent = (ReceiveExternalFilesActivity) getActivity();
  270. parent.setAccount(parent.mAccountManager.getAccountsByType(MainApp.getAccountType())[which]);
  271. parent.onAccountSet(parent.mAccountWasRestored);
  272. dialog.dismiss();
  273. parent.mAccountSelected = true;
  274. parent.mAccountSelectionShowing = false;
  275. }
  276. });
  277. builder.setCancelable(true);
  278. return builder.create();
  279. }
  280. public void onCancel(DialogInterface dialog) {
  281. super.onCancel(dialog);
  282. final ReceiveExternalFilesActivity parent = (ReceiveExternalFilesActivity) getActivity();
  283. parent.mAccountSelectionShowing = false;
  284. parent.finish();
  285. }
  286. }
  287. public static class DialogInputUploadFilename extends DialogFragment {
  288. private final static String KEY_SUBJECT_TEXT = "SUBJECT_TEXT";
  289. private final static String KEY_EXTRA_TEXT = "EXTRA_TEXT";
  290. private List<String> mFilenameBase;
  291. private List<String> mFilenameSuffix;
  292. private List<String> mText;
  293. private Spinner mSpinner;
  294. public static DialogInputUploadFilename newInstance(
  295. String subjectText, String extraText
  296. ) {
  297. DialogInputUploadFilename dialog = new DialogInputUploadFilename();
  298. Bundle args = new Bundle();
  299. args.putString(KEY_SUBJECT_TEXT, subjectText);
  300. args.putString(KEY_EXTRA_TEXT, extraText);
  301. dialog.setArguments(args);
  302. return dialog;
  303. }
  304. @NonNull
  305. @Override
  306. public Dialog onCreateDialog(Bundle savedInstanceState) {
  307. mFilenameBase = new ArrayList<>();
  308. mFilenameSuffix = new ArrayList<>();
  309. mText = new ArrayList<>();
  310. String subjectText = getArguments().getString(KEY_SUBJECT_TEXT);
  311. String extraText = getArguments().getString(KEY_EXTRA_TEXT);
  312. LayoutInflater layout = LayoutInflater.from(getActivity().getBaseContext());
  313. View view = layout.inflate(R.layout.upload_file_dialog, null);
  314. ArrayAdapter<String> adapter
  315. = new ArrayAdapter<>(getActivity().getBaseContext(), android.R.layout.simple_spinner_item);
  316. adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  317. int selectPos = 0;
  318. String filename = renameSafeFilename(subjectText);
  319. if (filename == null) {
  320. filename = "";
  321. }
  322. adapter.add(getString(R.string.upload_file_dialog_filetype_snippet_text));
  323. mText.add(extraText);
  324. mFilenameBase.add(filename);
  325. mFilenameSuffix.add(TEXT_FILE_SUFFIX);
  326. if (isIntentStartWithUrl(extraText)) {
  327. String str = getString(R.string.upload_file_dialog_filetype_internet_shortcut);
  328. mText.add(internetShortcutUrlText(extraText));
  329. mFilenameBase.add(filename);
  330. mFilenameSuffix.add(URL_FILE_SUFFIX);
  331. adapter.add(String.format(str,URL_FILE_SUFFIX));
  332. selectPos = adapter.getCount()-1;
  333. mText.add(internetShortcutWeblocText(extraText));
  334. mFilenameBase.add(filename);
  335. mFilenameSuffix.add(WEBLOC_FILE_SUFFIX);
  336. adapter.add(String.format(str,WEBLOC_FILE_SUFFIX));
  337. mText.add(internetShortcutDesktopText(extraText, filename));
  338. mFilenameBase.add(filename);
  339. mFilenameSuffix.add(DESKTOP_FILE_SUFFIX);
  340. adapter.add(String.format(str,DESKTOP_FILE_SUFFIX));
  341. }
  342. if (isIntentFromGoogleMap(subjectText, extraText)) {
  343. String str = getString(R.string.upload_file_dialog_filetype_googlemap_shortcut);
  344. String texts[] = extraText.split("\n");
  345. mText.add(internetShortcutUrlText(texts[2]));
  346. mFilenameBase.add(texts[0]);
  347. mFilenameSuffix.add(URL_FILE_SUFFIX);
  348. adapter.add(String.format(str,URL_FILE_SUFFIX));
  349. selectPos = adapter.getCount()-1;
  350. mText.add(internetShortcutWeblocText(texts[2]));
  351. mFilenameBase.add(texts[0]);
  352. mFilenameSuffix.add(WEBLOC_FILE_SUFFIX);
  353. adapter.add(String.format(str,WEBLOC_FILE_SUFFIX));
  354. mText.add(internetShortcutDesktopText(texts[2], texts[0]));
  355. mFilenameBase.add(texts[0]);
  356. mFilenameSuffix.add(DESKTOP_FILE_SUFFIX);
  357. adapter.add(String.format(str,DESKTOP_FILE_SUFFIX));
  358. }
  359. final EditText userInput = (EditText) view.findViewById(R.id.user_input);
  360. setFilename(userInput, selectPos);
  361. userInput.requestFocus();
  362. final Spinner spinner = (Spinner) view.findViewById(R.id.file_type);
  363. setupSpinner(adapter, selectPos, userInput, spinner);
  364. if (adapter.getCount() == 1) {
  365. TextView label = (TextView) view.findViewById(R.id.label_file_type);
  366. label.setVisibility(View.GONE);
  367. spinner.setVisibility(View.GONE);
  368. }
  369. mSpinner = spinner;
  370. Dialog filenameDialog = createFilenameDialog(view, userInput, spinner);
  371. filenameDialog.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);
  372. return filenameDialog;
  373. }
  374. private void setupSpinner(ArrayAdapter<String> adapter, int selectPos, final EditText userInput, Spinner spinner) {
  375. spinner.setAdapter(adapter);
  376. spinner.setSelection(selectPos, false);
  377. spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
  378. @Override
  379. public void onItemSelected(AdapterView parent, View view, int position, long id) {
  380. Spinner spinner = (Spinner) parent;
  381. int selectPos = spinner.getSelectedItemPosition();
  382. setFilename(userInput, selectPos);
  383. }
  384. @Override
  385. public void onNothingSelected(AdapterView<?> parent) {
  386. // nothing to do
  387. }
  388. });
  389. }
  390. @NonNull
  391. private Dialog createFilenameDialog(View view, final EditText userInput, final Spinner spinner) {
  392. Builder builder = new Builder(getActivity());
  393. builder.setView(view);
  394. builder.setTitle(R.string.upload_file_dialog_title);
  395. builder.setPositiveButton(R.string.common_ok, new OnClickListener() {
  396. public void onClick(DialogInterface dialog,int id) {
  397. int selectPos = spinner.getSelectedItemPosition();
  398. // verify if file name has suffix
  399. String filename = userInput.getText().toString();
  400. String suffix = mFilenameSuffix.get(selectPos);
  401. if (!filename.endsWith(suffix)){
  402. filename += suffix;
  403. }
  404. File file = createTempFile("tmp.tmp", mText.get(selectPos));
  405. if (file == null) {
  406. ((ReceiveExternalFilesActivity)getActivity()).finish();
  407. }
  408. String tmpname = file.getAbsolutePath();
  409. ((ReceiveExternalFilesActivity)getActivity()).uploadFile(tmpname, filename);
  410. }
  411. });
  412. builder.setNegativeButton(R.string.common_cancel, new OnClickListener() {
  413. public void onClick(DialogInterface dialog,int id) {
  414. dialog.cancel();
  415. }
  416. });
  417. return builder.create();
  418. }
  419. public void onPause() {
  420. hideSpinnerDropDown(mSpinner);
  421. super.onPause();
  422. }
  423. private void hideSpinnerDropDown(Spinner spinner) {
  424. try {
  425. Method method = Spinner.class.getDeclaredMethod("onDetachedFromWindow");
  426. method.setAccessible(true);
  427. method.invoke(spinner);
  428. } catch (Exception e) {
  429. Log_OC.e(TAG, "onDetachedFromWindow", e);
  430. }
  431. }
  432. private void setFilename(EditText inputText, int selectPos)
  433. {
  434. String filename = mFilenameBase.get(selectPos) + mFilenameSuffix.get(selectPos);
  435. inputText.setText(filename);
  436. int selectionStart = 0;
  437. int extensionStart = filename.lastIndexOf(".");
  438. int selectionEnd = (extensionStart >= 0) ? extensionStart : filename.length();
  439. if (selectionEnd >= 0) {
  440. inputText.setSelection(
  441. Math.min(selectionStart, selectionEnd),
  442. Math.max(selectionStart, selectionEnd));
  443. }
  444. }
  445. private boolean isIntentFromGoogleMap(String subjectText, String extraText) {
  446. String texts[] = extraText.split("\n");
  447. if (texts.length != 3)
  448. return false;
  449. if (texts[0].length() == 0 || !subjectText.equals(texts[0]))
  450. return false;
  451. return texts[2].startsWith("https://goo.gl/maps/");
  452. }
  453. private boolean isIntentStartWithUrl(String extraText) {
  454. return (extraText.startsWith("http://") || extraText.startsWith("https://"));
  455. }
  456. @Nullable
  457. private String renameSafeFilename(String filename) {
  458. String safeFilename = filename;
  459. safeFilename = safeFilename.replaceAll("[?]", "_");
  460. safeFilename = safeFilename.replaceAll("\"", "_");
  461. safeFilename = safeFilename.replaceAll("/", "_");
  462. safeFilename = safeFilename.replaceAll("<", "_");
  463. safeFilename = safeFilename.replaceAll(">", "_");
  464. safeFilename = safeFilename.replaceAll("[*]", "_");
  465. safeFilename = safeFilename.replaceAll("[|]", "_");
  466. safeFilename = safeFilename.replaceAll(";", "_");
  467. safeFilename = safeFilename.replaceAll("=", "_");
  468. safeFilename = safeFilename.replaceAll(",", "_");
  469. try {
  470. int maxLength = 128;
  471. if (safeFilename.getBytes(FILENAME_ENCODING).length > maxLength) {
  472. safeFilename = new String(safeFilename.getBytes(FILENAME_ENCODING), 0, maxLength, FILENAME_ENCODING);
  473. }
  474. } catch (UnsupportedEncodingException e) {
  475. Log_OC.e(TAG, "rename failed ", e);
  476. return null;
  477. }
  478. return safeFilename;
  479. }
  480. private String internetShortcutUrlText(String url) {
  481. return "[InternetShortcut]\r\n" +
  482. "URL=" + url + "\r\n";
  483. }
  484. private String internetShortcutWeblocText(String url) {
  485. return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
  486. "<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n" +
  487. "<plist version=\"1.0\">\n" +
  488. "<dict>\n" +
  489. "<key>URL</key>\n" +
  490. "<string>" + url + "</string>\n" +
  491. "</dict>\n" +
  492. "</plist>\n";
  493. }
  494. private String internetShortcutDesktopText(String url, String filename) {
  495. return "[Desktop Entry]\n" +
  496. "Encoding=UTF-8\n" +
  497. "Name=" + filename + "\n" +
  498. "Type=Link\n" +
  499. "URL=" + url + "\n" +
  500. "Icon=text-html";
  501. }
  502. @Nullable
  503. private File createTempFile(String filename, String text) {
  504. File file = new File(((ReceiveExternalFilesActivity)getActivity()).getCacheDir(), filename);
  505. FileWriter fw = null;
  506. try {
  507. fw = new FileWriter(file);
  508. fw.write(text);
  509. } catch (IOException e) {
  510. Log_OC.d(TAG, "Error ", e);
  511. return null;
  512. } finally {
  513. if (fw != null) {
  514. try {
  515. fw.close();
  516. } catch (IOException e) {
  517. Log_OC.d(TAG, "Error closing file writer ", e);
  518. }
  519. }
  520. }
  521. return file;
  522. }
  523. }
  524. @Override
  525. public void onBackPressed() {
  526. if (mParents.size() <= 1) {
  527. super.onBackPressed();
  528. } else {
  529. mParents.pop();
  530. String full_path = generatePath(mParents);
  531. startSyncFolderOperation(getStorageManager().getFileByPath(full_path));
  532. populateDirectoryList();
  533. }
  534. }
  535. @Override
  536. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  537. // click on folder in the list
  538. Log_OC.d(TAG, "on item click");
  539. Vector<OCFile> tmpfiles = getStorageManager().getFolderContent(mFile , false);
  540. sortFileList(tmpfiles);
  541. if (tmpfiles.size() <= 0) {
  542. return;
  543. }
  544. // filter on dirtype
  545. Vector<OCFile> files = new Vector<>();
  546. for (OCFile f : tmpfiles) {
  547. files.add(f);
  548. }
  549. if (files.size() < position) {
  550. throw new IndexOutOfBoundsException("Incorrect item selected");
  551. }
  552. if (files.get(position).isFolder()){
  553. OCFile folderToEnter = files.get(position);
  554. startSyncFolderOperation(folderToEnter);
  555. mParents.push(folderToEnter.getFileName());
  556. populateDirectoryList();
  557. }
  558. }
  559. @Override
  560. public void onClick(View v) {
  561. // click on button
  562. switch (v.getId()) {
  563. case R.id.uploader_choose_folder:
  564. mUploadPath = ""; // first element in mParents is root dir, represented by "";
  565. // init mUploadPath with "/" results in a "//" prefix
  566. for (String p : mParents) {
  567. mUploadPath += p + OCFile.PATH_SEPARATOR;
  568. }
  569. if (mUploadFromTmpFile){
  570. DialogInputUploadFilename dialog = DialogInputUploadFilename.newInstance(mSubjectText, mExtraText);
  571. dialog.show(getSupportFragmentManager(), null);
  572. } else {
  573. Log_OC.d(TAG, "Uploading file to dir " + mUploadPath);
  574. uploadFiles();
  575. }
  576. break;
  577. case R.id.uploader_cancel:
  578. finish();
  579. break;
  580. default:
  581. throw new IllegalArgumentException("Wrong element clicked");
  582. }
  583. }
  584. @Override
  585. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  586. super.onActivityResult(requestCode, resultCode, data);
  587. Log_OC.i(TAG, "result received. req: " + requestCode + " res: " + resultCode);
  588. if (requestCode == REQUEST_CODE__SETUP_ACCOUNT) {
  589. if (resultCode == RESULT_CANCELED) {
  590. finish();
  591. }
  592. Account[] accounts = mAccountManager.getAccountsByType(MainApp.getAuthTokenType());
  593. if (accounts.length == 0) {
  594. DialogNoAccount dialog = new DialogNoAccount();
  595. dialog.show(getSupportFragmentManager(), null);
  596. } else {
  597. // there is no need for checking for is there more then one
  598. // account at this point
  599. // since account setup can set only one account at time
  600. setAccount(accounts[0]);
  601. populateDirectoryList();
  602. }
  603. }
  604. }
  605. private void populateDirectoryList() {
  606. setContentView(R.layout.uploader_layout);
  607. setupToolbar();
  608. ActionBar actionBar = getSupportActionBar();
  609. ListView mListView = (ListView) findViewById(android.R.id.list);
  610. String current_dir = mParents.peek();
  611. if (current_dir.equals("")) {
  612. actionBar.setTitle(getString(R.string.uploader_top_message));
  613. } else {
  614. actionBar.setTitle(current_dir);
  615. }
  616. boolean notRoot = (mParents.size() > 1);
  617. actionBar.setDisplayHomeAsUpEnabled(notRoot);
  618. actionBar.setHomeButtonEnabled(notRoot);
  619. String full_path = generatePath(mParents);
  620. Log_OC.d(TAG, "Populating view with content of : " + full_path);
  621. mFile = getStorageManager().getFileByPath(full_path);
  622. if (mFile != null) {
  623. Vector<OCFile> files = getStorageManager().getFolderContent(mFile, false);
  624. sortFileList(files);
  625. List<HashMap<String, Object>> data = new LinkedList<>();
  626. for (OCFile f : files) {
  627. HashMap<String, Object> h = new HashMap<>();
  628. h.put("dirname", f);
  629. data.add(h);
  630. }
  631. UploaderAdapter sa = new UploaderAdapter(this,
  632. data,
  633. R.layout.uploader_list_item_layout,
  634. new String[] {"dirname"},
  635. new int[] {R.id.filename},
  636. getStorageManager(), getAccount());
  637. mListView.setAdapter(sa);
  638. Button btnChooseFolder = (Button) findViewById(R.id.uploader_choose_folder);
  639. btnChooseFolder.setOnClickListener(this);
  640. Button btnNewFolder = (Button) findViewById(R.id.uploader_cancel);
  641. btnNewFolder.setOnClickListener(this);
  642. mListView.setOnItemClickListener(this);
  643. }
  644. }
  645. @Override
  646. public void onSavedCertificate() {
  647. startSyncFolderOperation(getCurrentDir());
  648. }
  649. private void startSyncFolderOperation(OCFile folder) {
  650. long currentSyncTime = System.currentTimeMillis();
  651. mSyncInProgress = true;
  652. // perform folder synchronization
  653. RemoteOperation synchFolderOp = new RefreshFolderOperation( folder,
  654. currentSyncTime,
  655. false,
  656. false,
  657. false,
  658. getStorageManager(),
  659. getAccount(),
  660. getApplicationContext()
  661. );
  662. synchFolderOp.execute(getAccount(), this, null, null);
  663. }
  664. private Vector<OCFile> sortFileList(Vector<OCFile> files) {
  665. // Read sorting order, default to sort by name ascending
  666. FileStorageUtils.mSortOrder = PreferenceManager.getSortOrder(this);
  667. FileStorageUtils.mSortAscending = PreferenceManager.getSortAscending(this);
  668. return FileStorageUtils.sortOcFolder(files);
  669. }
  670. private String generatePath(Stack<String> dirs) {
  671. String full_path = "";
  672. for (String a : dirs) {
  673. full_path += a + "/";
  674. }
  675. return full_path;
  676. }
  677. private void prepareStreamsToUpload() {
  678. Intent intent = getIntent();
  679. if (intent.getAction().equals(Intent.ACTION_SEND)) {
  680. mStreamsToUpload = new ArrayList<>();
  681. mStreamsToUpload.add(intent.getParcelableExtra(Intent.EXTRA_STREAM));
  682. } else if (intent.getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
  683. mStreamsToUpload = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
  684. }
  685. if (mStreamsToUpload == null || mStreamsToUpload.get(0) == null) {
  686. mStreamsToUpload = null;
  687. saveTextsFromIntent(intent);
  688. }
  689. }
  690. private void saveTextsFromIntent(Intent intent) {
  691. if (!intent.getType().equals("text/plain")) {
  692. return;
  693. }
  694. mUploadFromTmpFile = true;
  695. mSubjectText = intent.getStringExtra(Intent.EXTRA_SUBJECT);
  696. if (mSubjectText == null) {
  697. mSubjectText = intent.getStringExtra(Intent.EXTRA_TITLE);
  698. if (mSubjectText == null) {
  699. mSubjectText = DateFormat.format("yyyyMMdd_kkmmss", Calendar.getInstance()).toString();
  700. }
  701. }
  702. mExtraText = intent.getStringExtra(Intent.EXTRA_TEXT);
  703. }
  704. private boolean somethingToUpload() {
  705. return (mStreamsToUpload != null && mStreamsToUpload.size() > 0 && mStreamsToUpload.get(0) != null ||
  706. mUploadFromTmpFile);
  707. }
  708. public void uploadFile(String tmpname, String filename) {
  709. FileUploader.UploadRequester requester = new FileUploader.UploadRequester();
  710. requester.uploadNewFile(
  711. getBaseContext(),
  712. getAccount(),
  713. tmpname,
  714. mFile.getRemotePath() + filename,
  715. FileUploader.LOCAL_BEHAVIOUR_COPY,
  716. null,
  717. true,
  718. UploadFileOperation.CREATED_BY_USER
  719. );
  720. finish();
  721. }
  722. @SuppressLint("NewApi")
  723. public void uploadFiles() {
  724. UriUploader uploader = new UriUploader(
  725. this,
  726. mStreamsToUpload,
  727. mUploadPath,
  728. getAccount(),
  729. FileUploader.LOCAL_BEHAVIOUR_FORGET,
  730. true, // Show waiting dialog while file is being copied from private storage
  731. this // Copy temp task listener
  732. );
  733. UriUploader.UriUploaderResultCode resultCode = uploader.uploadUris();
  734. // Save the path to shared preferences; even if upload is not possible, user chose the folder
  735. PreferenceManager.setLastUploadPath(this, mUploadPath);
  736. if (resultCode == UriUploader.UriUploaderResultCode.OK) {
  737. finish();
  738. } else {
  739. int messageResTitle = R.string.uploader_error_title_file_cannot_be_uploaded;
  740. int messageResId = R.string.common_error_unknown;
  741. if (resultCode == UriUploader.UriUploaderResultCode.ERROR_NO_FILE_TO_UPLOAD) {
  742. messageResId = R.string.uploader_error_message_no_file_to_upload;
  743. messageResTitle = R.string.uploader_error_title_no_file_to_upload;
  744. } else if (resultCode == UriUploader.UriUploaderResultCode.ERROR_READ_PERMISSION_NOT_GRANTED) {
  745. messageResId = R.string.uploader_error_message_read_permission_not_granted;
  746. } else if (resultCode == UriUploader.UriUploaderResultCode.ERROR_UNKNOWN) {
  747. messageResId = R.string.common_error_unknown;
  748. }
  749. showErrorDialog(
  750. messageResId,
  751. messageResTitle
  752. );
  753. }
  754. }
  755. @Override
  756. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  757. super.onRemoteOperationFinish(operation, result);
  758. if (operation instanceof CreateFolderOperation) {
  759. onCreateFolderOperationFinish((CreateFolderOperation) operation, result);
  760. }
  761. }
  762. /**
  763. * Updates the view associated to the activity after the finish of an operation
  764. * trying create a new folder
  765. *
  766. * @param operation Creation operation performed.
  767. * @param result Result of the creation.
  768. */
  769. private void onCreateFolderOperationFinish(CreateFolderOperation operation,
  770. RemoteOperationResult result) {
  771. if (result.isSuccess()) {
  772. String remotePath = operation.getRemotePath().substring(0, operation.getRemotePath().length() - 1);
  773. String newFolder = remotePath.substring(remotePath.lastIndexOf('/') + 1);
  774. mParents.push(newFolder);
  775. populateDirectoryList();
  776. } else {
  777. try {
  778. Toast msg = Toast.makeText(this,
  779. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  780. Toast.LENGTH_LONG);
  781. msg.show();
  782. } catch (NotFoundException e) {
  783. Log_OC.e(TAG, "Error while trying to show fail message ", e);
  784. }
  785. }
  786. }
  787. /**
  788. * Loads the target folder initialize shown to the user.
  789. * <p/>
  790. * The target account has to be chosen before this method is called.
  791. */
  792. private void initTargetFolder() {
  793. if (getStorageManager() == null) {
  794. throw new IllegalStateException("Do not call this method before " +
  795. "initializing mStorageManager");
  796. }
  797. String lastPath = PreferenceManager.getLastUploadPath(this);
  798. // "/" equals root-directory
  799. if (lastPath.equals("/")) {
  800. mParents.add("");
  801. } else {
  802. String[] dir_names = lastPath.split("/");
  803. mParents.clear();
  804. for (String dir : dir_names) {
  805. mParents.add(dir);
  806. }
  807. }
  808. //Make sure that path still exists, if it doesn't pop the stack and try the previous path
  809. while (!getStorageManager().fileExists(generatePath(mParents)) && mParents.size() > 1) {
  810. mParents.pop();
  811. }
  812. }
  813. @Override
  814. public boolean onCreateOptionsMenu(Menu menu) {
  815. MenuInflater inflater = getMenuInflater();
  816. inflater.inflate(R.menu.main_menu, menu);
  817. menu.findItem(R.id.action_sort).setVisible(false);
  818. menu.findItem(R.id.action_switch_view).setVisible(false);
  819. menu.findItem(R.id.action_sync_account).setVisible(false);
  820. return true;
  821. }
  822. @Override
  823. public boolean onOptionsItemSelected(MenuItem item) {
  824. boolean retval = true;
  825. switch (item.getItemId()) {
  826. case R.id.action_create_dir:
  827. CreateFolderDialogFragment dialog = CreateFolderDialogFragment.newInstance(mFile);
  828. dialog.show(
  829. getSupportFragmentManager(),
  830. CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT);
  831. break;
  832. case android.R.id.home:
  833. if ((mParents.size() > 1)) {
  834. onBackPressed();
  835. }
  836. break;
  837. default:
  838. retval = super.onOptionsItemSelected(item);
  839. }
  840. return retval;
  841. }
  842. private OCFile getCurrentFolder(){
  843. OCFile file = mFile;
  844. if (file != null) {
  845. if (file.isFolder()) {
  846. return file;
  847. } else if (getStorageManager() != null) {
  848. return getStorageManager().getFileByPath(file.getParentRemotePath());
  849. }
  850. }
  851. return null;
  852. }
  853. private void browseToRoot() {
  854. OCFile root = getStorageManager().getFileByPath(OCFile.ROOT_PATH);
  855. mFile = root;
  856. startSyncFolderOperation(root);
  857. }
  858. private class SyncBroadcastReceiver extends BroadcastReceiver {
  859. /**
  860. * {@link BroadcastReceiver} to enable syncing feedback in UI
  861. */
  862. @Override
  863. public void onReceive(Context context, Intent intent) {
  864. try {
  865. String event = intent.getAction();
  866. Log_OC.d(TAG, "Received broadcast " + event);
  867. String accountName = intent.getStringExtra(FileSyncAdapter.EXTRA_ACCOUNT_NAME);
  868. String synchFolderRemotePath =
  869. intent.getStringExtra(FileSyncAdapter.EXTRA_FOLDER_PATH);
  870. RemoteOperationResult synchResult =
  871. (RemoteOperationResult) intent.getSerializableExtra(
  872. FileSyncAdapter.EXTRA_RESULT);
  873. boolean sameAccount = (getAccount() != null &&
  874. accountName.equals(getAccount().name) && getStorageManager() != null);
  875. if (sameAccount) {
  876. if (FileSyncAdapter.EVENT_FULL_SYNC_START.equals(event)) {
  877. mSyncInProgress = true;
  878. } else {
  879. OCFile currentFile = (mFile == null) ? null :
  880. getStorageManager().getFileByPath(mFile.getRemotePath());
  881. OCFile currentDir = (getCurrentFolder() == null) ? null :
  882. getStorageManager().getFileByPath(getCurrentFolder().getRemotePath());
  883. if (currentDir == null) {
  884. // current folder was removed from the server
  885. Toast.makeText(context,
  886. String.format(
  887. getString(R.string.sync_current_folder_was_removed),
  888. getCurrentFolder().getFileName()),
  889. Toast.LENGTH_LONG)
  890. .show();
  891. browseToRoot();
  892. } else {
  893. if (currentFile == null && !mFile.isFolder()) {
  894. // currently selected file was removed in the server, and now we know it
  895. currentFile = currentDir;
  896. }
  897. if (currentDir.getRemotePath().equals(synchFolderRemotePath)) {
  898. populateDirectoryList();
  899. }
  900. mFile = currentFile;
  901. }
  902. mSyncInProgress = (!FileSyncAdapter.EVENT_FULL_SYNC_END.equals(event) &&
  903. !RefreshFolderOperation.EVENT_SINGLE_FOLDER_SHARES_SYNCED.equals(event));
  904. if (RefreshFolderOperation.EVENT_SINGLE_FOLDER_CONTENTS_SYNCED.
  905. equals(event) &&
  906. /// TODO refactor and make common
  907. synchResult != null && !synchResult.isSuccess()) {
  908. if(synchResult.getCode() == ResultCode.UNAUTHORIZED ||
  909. (synchResult.isException() && synchResult.getException()
  910. instanceof AuthenticatorException)) {
  911. requestCredentialsUpdate(context);
  912. } else if(RemoteOperationResult.ResultCode.SSL_RECOVERABLE_PEER_UNVERIFIED.equals(synchResult.getCode())) {
  913. showUntrustedCertDialog(synchResult);
  914. }
  915. }
  916. }
  917. removeStickyBroadcast(intent);
  918. Log_OC.d(TAG, "Setting progress visibility to " + mSyncInProgress);
  919. }
  920. } catch (RuntimeException e) {
  921. // avoid app crashes after changing the serial id of RemoteOperationResult
  922. // in owncloud library with broadcast notifications pending to process
  923. removeStickyBroadcast(intent);
  924. }
  925. }
  926. }
  927. /**
  928. * Process the result of CopyAndUploadContentUrisTask
  929. */
  930. @Override
  931. public void onTmpFilesCopied(ResultCode result) {
  932. dismissLoadingDialog();
  933. finish();
  934. }
  935. /**
  936. * Show an error dialog, forcing the user to click a single button to exit the activity
  937. *
  938. * @param messageResId Resource id of the message to show in the dialog.
  939. * @param messageResTitle Resource id of the title to show in the dialog. 0 to show default alert message.
  940. * -1 to show no title.
  941. */
  942. private void showErrorDialog(int messageResId, int messageResTitle) {
  943. ConfirmationDialogFragment errorDialog = ConfirmationDialogFragment.newInstance(
  944. messageResId,
  945. new String[]{getString(R.string.app_name)}, // see uploader_error_message_* in strings.xml
  946. messageResTitle,
  947. R.string.common_back,
  948. -1,
  949. -1
  950. );
  951. errorDialog.setCancelable(false);
  952. errorDialog.setOnConfirmationListener(
  953. new ConfirmationDialogFragment.ConfirmationDialogFragmentListener() {
  954. @Override
  955. public void onConfirmation(String callerTag) {
  956. finish();
  957. }
  958. @Override
  959. public void onNeutral(String callerTag) {}
  960. @Override
  961. public void onCancel(String callerTag) {}
  962. }
  963. );
  964. errorDialog.show(getSupportFragmentManager(), FTAG_ERROR_FRAGMENT);
  965. }
  966. }