ReceiveExternalFilesActivity.java 48 KB

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