ReceiveExternalFilesActivity.java 49 KB

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