Uploader.java 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  1. /**
  2. * ownCloud Android client application
  3. *
  4. * @author Bartek Przybylski
  5. * @author masensio
  6. * Copyright (C) 2012 Bartek Przybylski
  7. * Copyright (C) 2015 ownCloud Inc.
  8. *
  9. * This program is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2,
  11. * as published by the Free Software Foundation.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  20. *
  21. */
  22. package com.owncloud.android.ui.activity;
  23. import java.io.File;
  24. import java.util.ArrayList;
  25. import java.util.HashMap;
  26. import java.util.LinkedList;
  27. import java.util.List;
  28. import java.util.Stack;
  29. import java.util.Vector;
  30. import android.accounts.Account;
  31. import android.accounts.AccountManager;
  32. import android.support.v7.app.AlertDialog;
  33. import android.support.v7.app.AlertDialog.Builder;
  34. import android.app.Dialog;
  35. import android.app.ProgressDialog;
  36. import android.content.Context;
  37. import android.content.DialogInterface;
  38. import android.content.DialogInterface.OnCancelListener;
  39. import android.content.DialogInterface.OnClickListener;
  40. import android.content.Intent;
  41. import android.content.SharedPreferences;
  42. import android.content.res.Resources.NotFoundException;
  43. import android.database.Cursor;
  44. import android.net.Uri;
  45. import android.os.Bundle;
  46. import android.os.Parcelable;
  47. import android.preference.PreferenceManager;
  48. import android.provider.MediaStore;
  49. import android.provider.MediaStore.Audio;
  50. import android.provider.MediaStore.Images;
  51. import android.provider.MediaStore.Video;
  52. import android.support.v4.app.Fragment;
  53. import android.support.v4.app.FragmentManager;
  54. import android.support.v4.app.FragmentTransaction;
  55. import android.support.v7.app.ActionBar;
  56. import android.view.Menu;
  57. import android.view.MenuInflater;
  58. import android.view.MenuItem;
  59. import android.view.View;
  60. import android.widget.AdapterView;
  61. import android.widget.AdapterView.OnItemClickListener;
  62. import android.widget.Button;
  63. import android.widget.EditText;
  64. import android.widget.ListView;
  65. import android.widget.ProgressBar;
  66. import android.widget.SimpleAdapter;
  67. import android.widget.Toast;
  68. import com.owncloud.android.MainApp;
  69. import com.owncloud.android.R;
  70. import com.owncloud.android.authentication.AccountAuthenticator;
  71. import com.owncloud.android.datamodel.OCFile;
  72. import com.owncloud.android.files.services.FileUploader;
  73. import com.owncloud.android.lib.common.utils.Log_OC;
  74. import com.owncloud.android.lib.common.operations.RemoteOperation;
  75. import com.owncloud.android.lib.common.operations.RemoteOperationResult;
  76. import com.owncloud.android.operations.CreateFolderOperation;
  77. import com.owncloud.android.ui.dialog.CreateFolderDialogFragment;
  78. import com.owncloud.android.ui.dialog.LoadingDialog;
  79. import com.owncloud.android.utils.CopyTmpFileAsyncTask;
  80. import com.owncloud.android.utils.DisplayUtils;
  81. import com.owncloud.android.utils.ErrorMessageAdapter;
  82. /**
  83. * This can be used to upload things to an ownCloud instance.
  84. */
  85. public class Uploader extends FileActivity
  86. implements OnItemClickListener, android.view.View.OnClickListener,
  87. CopyTmpFileAsyncTask.OnCopyTmpFileTaskListener {
  88. private static final String TAG = Uploader.class.getSimpleName();
  89. private AccountManager mAccountManager;
  90. private Stack<String> mParents;
  91. private ArrayList<Parcelable> mStreamsToUpload;
  92. private boolean mCreateDir;
  93. private String mUploadPath;
  94. private OCFile mFile;
  95. private boolean mAccountSelected;
  96. private boolean mAccountSelectionShowing;
  97. private ArrayList<String> mRemoteCacheData;
  98. private int mNumCacheFile;
  99. private final static int DIALOG_NO_ACCOUNT = 0;
  100. private final static int DIALOG_WAITING = 1;
  101. private final static int DIALOG_NO_STREAM = 2;
  102. private final static int DIALOG_MULTIPLE_ACCOUNT = 3;
  103. private final static int REQUEST_CODE_SETUP_ACCOUNT = 0;
  104. private final static String KEY_PARENTS = "PARENTS";
  105. private final static String KEY_FILE = "FILE";
  106. private final static String KEY_ACCOUNT_SELECTED = "ACCOUNT_SELECTED";
  107. private final static String KEY_ACCOUNT_SELECTION_SHOWING = "ACCOUNT_SELECTION_SHOWING";
  108. private final static String KEY_NUM_CACHE_FILE = "NUM_CACHE_FILE";
  109. private final static String KEY_REMOTE_CACHE_DATA = "REMOTE_CACHE_DATA";
  110. private static final String DIALOG_WAIT_COPY_FILE = "DIALOG_WAIT_COPY_FILE";
  111. @Override
  112. protected void onCreate(Bundle savedInstanceState) {
  113. prepareStreamsToUpload();
  114. if (savedInstanceState == null) {
  115. mParents = new Stack<String>();
  116. mAccountSelected = false;
  117. mAccountSelectionShowing = false;
  118. mNumCacheFile = 0;
  119. // ArrayList for files with path in private storage
  120. mRemoteCacheData = new ArrayList<String>();
  121. } else {
  122. mParents = (Stack<String>) savedInstanceState.getSerializable(KEY_PARENTS);
  123. mFile = savedInstanceState.getParcelable(KEY_FILE);
  124. mAccountSelected = savedInstanceState.getBoolean(KEY_ACCOUNT_SELECTED);
  125. mAccountSelectionShowing = savedInstanceState.getBoolean(KEY_ACCOUNT_SELECTION_SHOWING);
  126. mNumCacheFile = savedInstanceState.getInt(KEY_NUM_CACHE_FILE);
  127. mRemoteCacheData = savedInstanceState.getStringArrayList(KEY_REMOTE_CACHE_DATA);
  128. }
  129. super.onCreate(savedInstanceState);
  130. if (mAccountSelected) {
  131. setAccount((Account) savedInstanceState.getParcelable(FileActivity.EXTRA_ACCOUNT));
  132. }
  133. }
  134. @Override
  135. protected void setAccount(Account account, boolean savedAccount) {
  136. if (somethingToUpload()) {
  137. mAccountManager = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
  138. Account[] accounts = mAccountManager.getAccountsByType(MainApp.getAccountType());
  139. if (accounts.length == 0) {
  140. Log_OC.i(TAG, "No ownCloud account is available");
  141. showDialog(DIALOG_NO_ACCOUNT);
  142. } else if (accounts.length > 1 && !mAccountSelected && !mAccountSelectionShowing) {
  143. Log_OC.i(TAG, "More than one ownCloud is available");
  144. showDialog(DIALOG_MULTIPLE_ACCOUNT);
  145. mAccountSelectionShowing = true;
  146. } else {
  147. if (!savedAccount) {
  148. setAccount(accounts[0]);
  149. }
  150. }
  151. } else {
  152. showDialog(DIALOG_NO_STREAM);
  153. }
  154. super.setAccount(account, savedAccount);
  155. }
  156. @Override
  157. protected void onAccountSet(boolean stateWasRecovered) {
  158. super.onAccountSet(mAccountWasRestored);
  159. initTargetFolder();
  160. populateDirectoryList();
  161. }
  162. @Override
  163. protected void onSaveInstanceState(Bundle outState) {
  164. Log_OC.d(TAG, "onSaveInstanceState() start");
  165. super.onSaveInstanceState(outState);
  166. outState.putSerializable(KEY_PARENTS, mParents);
  167. //outState.putParcelable(KEY_ACCOUNT, mAccount);
  168. outState.putParcelable(KEY_FILE, mFile);
  169. outState.putBoolean(KEY_ACCOUNT_SELECTED, mAccountSelected);
  170. outState.putBoolean(KEY_ACCOUNT_SELECTION_SHOWING, mAccountSelectionShowing);
  171. outState.putInt(KEY_NUM_CACHE_FILE, mNumCacheFile);
  172. outState.putStringArrayList(KEY_REMOTE_CACHE_DATA, mRemoteCacheData);
  173. outState.putParcelable(FileActivity.EXTRA_ACCOUNT, getAccount());
  174. Log_OC.d(TAG, "onSaveInstanceState() end");
  175. }
  176. @Override
  177. protected Dialog onCreateDialog(final int id) {
  178. final AlertDialog.Builder builder = new Builder(this);
  179. switch (id) {
  180. case DIALOG_WAITING:
  181. final ProgressDialog pDialog = new ProgressDialog(this, R.style.ProgressDialogTheme);
  182. pDialog.setIndeterminate(false);
  183. pDialog.setCancelable(false);
  184. pDialog.setMessage(getResources().getString(R.string.uploader_info_uploading));
  185. pDialog.setOnShowListener(new DialogInterface.OnShowListener() {
  186. @Override
  187. public void onShow(DialogInterface dialog) {
  188. ProgressBar v = (ProgressBar) pDialog.findViewById(android.R.id.progress);
  189. v.getIndeterminateDrawable().setColorFilter(getResources().getColor(R.color.color_accent),
  190. android.graphics.PorterDuff.Mode.MULTIPLY);
  191. }
  192. });
  193. return pDialog;
  194. case DIALOG_NO_ACCOUNT:
  195. builder.setIcon(android.R.drawable.ic_dialog_alert);
  196. builder.setTitle(R.string.uploader_wrn_no_account_title);
  197. builder.setMessage(String.format(
  198. getString(R.string.uploader_wrn_no_account_text), getString(R.string.app_name)));
  199. builder.setCancelable(false);
  200. builder.setPositiveButton(R.string.uploader_wrn_no_account_setup_btn_text, new OnClickListener() {
  201. @Override
  202. public void onClick(DialogInterface dialog, int which) {
  203. if (android.os.Build.VERSION.SDK_INT >
  204. android.os.Build.VERSION_CODES.ECLAIR_MR1) {
  205. // using string value since in API7 this
  206. // constatn is not defined
  207. // in API7 < this constatant is defined in
  208. // Settings.ADD_ACCOUNT_SETTINGS
  209. // and Settings.EXTRA_AUTHORITIES
  210. Intent intent = new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT);
  211. intent.putExtra("authorities", new String[] { MainApp.getAuthTokenType() });
  212. startActivityForResult(intent, REQUEST_CODE_SETUP_ACCOUNT);
  213. } else {
  214. // since in API7 there is no direct call for
  215. // account setup, so we need to
  216. // show our own AccountSetupAcricity, get
  217. // desired results and setup
  218. // everything for ourself
  219. Intent intent = new Intent(getBaseContext(), AccountAuthenticator.class);
  220. startActivityForResult(intent, REQUEST_CODE_SETUP_ACCOUNT);
  221. }
  222. }
  223. });
  224. builder.setNegativeButton(R.string.uploader_wrn_no_account_quit_btn_text, new OnClickListener() {
  225. @Override
  226. public void onClick(DialogInterface dialog, int which) {
  227. finish();
  228. }
  229. });
  230. return builder.create();
  231. case DIALOG_MULTIPLE_ACCOUNT:
  232. CharSequence ac[] = new CharSequence[
  233. mAccountManager.getAccountsByType(MainApp.getAccountType()).length];
  234. for (int i = 0; i < ac.length; ++i) {
  235. ac[i] = DisplayUtils.convertIdn(
  236. mAccountManager.getAccountsByType(MainApp.getAccountType())[i].name, false);
  237. }
  238. builder.setTitle(R.string.common_choose_account);
  239. builder.setItems(ac, new OnClickListener() {
  240. @Override
  241. public void onClick(DialogInterface dialog, int which) {
  242. setAccount(mAccountManager.getAccountsByType(MainApp.getAccountType())[which]);
  243. onAccountSet(mAccountWasRestored);
  244. dialog.dismiss();
  245. mAccountSelected = true;
  246. mAccountSelectionShowing = false;
  247. }
  248. });
  249. builder.setCancelable(true);
  250. builder.setOnCancelListener(new OnCancelListener() {
  251. @Override
  252. public void onCancel(DialogInterface dialog) {
  253. mAccountSelectionShowing = false;
  254. dialog.cancel();
  255. finish();
  256. }
  257. });
  258. return builder.create();
  259. case DIALOG_NO_STREAM:
  260. builder.setIcon(android.R.drawable.ic_dialog_alert);
  261. builder.setTitle(R.string.uploader_wrn_no_content_title);
  262. builder.setMessage(R.string.uploader_wrn_no_content_text);
  263. builder.setCancelable(false);
  264. builder.setNegativeButton(R.string.common_cancel, new OnClickListener() {
  265. @Override
  266. public void onClick(DialogInterface dialog, int which) {
  267. finish();
  268. }
  269. });
  270. return builder.create();
  271. default:
  272. throw new IllegalArgumentException("Unknown dialog id: " + id);
  273. }
  274. }
  275. class a implements OnClickListener {
  276. String mPath;
  277. EditText mDirname;
  278. public a(String path, EditText dirname) {
  279. mPath = path;
  280. mDirname = dirname;
  281. }
  282. @Override
  283. public void onClick(DialogInterface dialog, int which) {
  284. Uploader.this.mUploadPath = mPath + mDirname.getText().toString();
  285. Uploader.this.mCreateDir = true;
  286. uploadFiles();
  287. }
  288. }
  289. @Override
  290. public void onBackPressed() {
  291. if (mParents.size() <= 1) {
  292. super.onBackPressed();
  293. return;
  294. } else {
  295. mParents.pop();
  296. populateDirectoryList();
  297. }
  298. }
  299. @Override
  300. public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
  301. // click on folder in the list
  302. Log_OC.d(TAG, "on item click");
  303. // TODO Enable when "On Device" is recovered ?
  304. Vector<OCFile> tmpfiles = getStorageManager().getFolderContent(mFile /*, false*/);
  305. if (tmpfiles.size() <= 0) return;
  306. // filter on dirtype
  307. Vector<OCFile> files = new Vector<OCFile>();
  308. for (OCFile f : tmpfiles)
  309. if (f.isFolder())
  310. files.add(f);
  311. if (files.size() < position) {
  312. throw new IndexOutOfBoundsException("Incorrect item selected");
  313. }
  314. mParents.push(files.get(position).getFileName());
  315. populateDirectoryList();
  316. }
  317. @Override
  318. public void onClick(View v) {
  319. // click on button
  320. switch (v.getId()) {
  321. case R.id.uploader_choose_folder:
  322. mUploadPath = ""; // first element in mParents is root dir, represented by "";
  323. // init mUploadPath with "/" results in a "//" prefix
  324. for (String p : mParents)
  325. mUploadPath += p + OCFile.PATH_SEPARATOR;
  326. Log_OC.d(TAG, "Uploading file to dir " + mUploadPath);
  327. uploadFiles();
  328. break;
  329. case R.id.uploader_cancel:
  330. finish();
  331. break;
  332. default:
  333. throw new IllegalArgumentException("Wrong element clicked");
  334. }
  335. }
  336. @Override
  337. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  338. super.onActivityResult(requestCode, resultCode, data);
  339. Log_OC.i(TAG, "result received. req: " + requestCode + " res: " + resultCode);
  340. if (requestCode == REQUEST_CODE_SETUP_ACCOUNT) {
  341. dismissDialog(DIALOG_NO_ACCOUNT);
  342. if (resultCode == RESULT_CANCELED) {
  343. finish();
  344. }
  345. Account[] accounts = mAccountManager.getAccountsByType(MainApp.getAuthTokenType());
  346. if (accounts.length == 0) {
  347. showDialog(DIALOG_NO_ACCOUNT);
  348. } else {
  349. // there is no need for checking for is there more then one
  350. // account at this point
  351. // since account setup can set only one account at time
  352. setAccount(accounts[0]);
  353. populateDirectoryList();
  354. }
  355. }
  356. }
  357. private void populateDirectoryList() {
  358. setContentView(R.layout.uploader_layout);
  359. ListView mListView = (ListView) findViewById(android.R.id.list);
  360. String current_dir = mParents.peek();
  361. if(current_dir.equals("")){
  362. getSupportActionBar().setTitle(getString(R.string.default_display_name_for_root_folder));
  363. }
  364. else{
  365. getSupportActionBar().setTitle(current_dir);
  366. }
  367. boolean notRoot = (mParents.size() > 1);
  368. ActionBar actionBar = getSupportActionBar();
  369. actionBar.setDisplayHomeAsUpEnabled(notRoot);
  370. actionBar.setHomeButtonEnabled(notRoot);
  371. String full_path = generatePath(mParents);
  372. Log_OC.d(TAG, "Populating view with content of : " + full_path);
  373. mFile = getStorageManager().getFileByPath(full_path);
  374. if (mFile != null) {
  375. // TODO Enable when "On Device" is recovered ?
  376. Vector<OCFile> files = getStorageManager().getFolderContent(mFile/*, false*/);
  377. List<HashMap<String, Object>> data = new LinkedList<HashMap<String,Object>>();
  378. for (OCFile f : files) {
  379. HashMap<String, Object> h = new HashMap<String, Object>();
  380. if (f.isFolder()) {
  381. h.put("dirname", f.getFileName());
  382. data.add(h);
  383. }
  384. }
  385. SimpleAdapter sa = new SimpleAdapter(this,
  386. data,
  387. R.layout.uploader_list_item_layout,
  388. new String[] {"dirname"},
  389. new int[] {R.id.filename});
  390. mListView.setAdapter(sa);
  391. Button btnChooseFolder = (Button) findViewById(R.id.uploader_choose_folder);
  392. btnChooseFolder.setOnClickListener(this);
  393. Button btnNewFolder = (Button) findViewById(R.id.uploader_cancel);
  394. btnNewFolder.setOnClickListener(this);
  395. mListView.setOnItemClickListener(this);
  396. }
  397. }
  398. private String generatePath(Stack<String> dirs) {
  399. String full_path = "";
  400. for (String a : dirs)
  401. full_path += a + "/";
  402. return full_path;
  403. }
  404. private void prepareStreamsToUpload() {
  405. if (getIntent().getAction().equals(Intent.ACTION_SEND)) {
  406. mStreamsToUpload = new ArrayList<Parcelable>();
  407. mStreamsToUpload.add(getIntent().getParcelableExtra(Intent.EXTRA_STREAM));
  408. } else if (getIntent().getAction().equals(Intent.ACTION_SEND_MULTIPLE)) {
  409. mStreamsToUpload = getIntent().getParcelableArrayListExtra(Intent.EXTRA_STREAM);
  410. }
  411. }
  412. private boolean somethingToUpload() {
  413. return (mStreamsToUpload != null && mStreamsToUpload.get(0) != null);
  414. }
  415. public void uploadFiles() {
  416. try {
  417. // ArrayList for files with path in external storage
  418. ArrayList<String> local = new ArrayList<String>();
  419. ArrayList<String> remote = new ArrayList<String>();
  420. // this checks the mimeType
  421. for (Parcelable mStream : mStreamsToUpload) {
  422. Uri uri = (Uri) mStream;
  423. String data = null;
  424. String filePath = "";
  425. if (uri != null) {
  426. if (uri.getScheme().equals("content")) {
  427. String mimeType = getContentResolver().getType(uri);
  428. if (mimeType.contains("image")) {
  429. String[] CONTENT_PROJECTION = { Images.Media.DATA,
  430. Images.Media.DISPLAY_NAME, Images.Media.MIME_TYPE,
  431. Images.Media.SIZE };
  432. Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null,
  433. null, null);
  434. c.moveToFirst();
  435. int index = c.getColumnIndex(Images.Media.DATA);
  436. data = c.getString(index);
  437. filePath = mUploadPath +
  438. c.getString(c.getColumnIndex(Images.Media.DISPLAY_NAME));
  439. } else if (mimeType.contains("video")) {
  440. String[] CONTENT_PROJECTION = { Video.Media.DATA,
  441. Video.Media.DISPLAY_NAME, Video.Media.MIME_TYPE,
  442. Video.Media.SIZE, Video.Media.DATE_MODIFIED };
  443. Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null,
  444. null, null);
  445. c.moveToFirst();
  446. int index = c.getColumnIndex(Video.Media.DATA);
  447. data = c.getString(index);
  448. filePath = mUploadPath +
  449. c.getString(c.getColumnIndex(Video.Media.DISPLAY_NAME));
  450. } else if (mimeType.contains("audio")) {
  451. String[] CONTENT_PROJECTION = { Audio.Media.DATA,
  452. Audio.Media.DISPLAY_NAME, Audio.Media.MIME_TYPE,
  453. Audio.Media.SIZE };
  454. Cursor c = getContentResolver().query(uri, CONTENT_PROJECTION, null,
  455. null, null);
  456. c.moveToFirst();
  457. int index = c.getColumnIndex(Audio.Media.DATA);
  458. data = c.getString(index);
  459. filePath = mUploadPath +
  460. c.getString(c.getColumnIndex(Audio.Media.DISPLAY_NAME));
  461. } else {
  462. Cursor cursor = getContentResolver().query(uri,
  463. new String[]{MediaStore.MediaColumns.DISPLAY_NAME},
  464. null, null, null);
  465. cursor.moveToFirst();
  466. int nameIndex = cursor.getColumnIndex(cursor.getColumnNames()[0]);
  467. if (nameIndex >= 0) {
  468. filePath = mUploadPath + cursor.getString(nameIndex);
  469. }
  470. }
  471. } else if (uri.getScheme().equals("file")) {
  472. filePath = Uri.decode(uri.toString()).replace(uri.getScheme() +
  473. "://", "");
  474. if (filePath.contains("mnt")) {
  475. String splitedFilePath[] = filePath.split("/mnt");
  476. filePath = splitedFilePath[1];
  477. }
  478. final File file = new File(filePath);
  479. data = file.getAbsolutePath();
  480. filePath = mUploadPath + file.getName();
  481. }
  482. else {
  483. throw new SecurityException();
  484. }
  485. if (data == null) {
  486. mRemoteCacheData.add(filePath);
  487. CopyTmpFileAsyncTask copyTask = new CopyTmpFileAsyncTask(this);
  488. Object[] params = { uri, filePath, mRemoteCacheData.size()-1,
  489. getAccount().name, getContentResolver()};
  490. mNumCacheFile++;
  491. showWaitingCopyDialog();
  492. copyTask.execute(params);
  493. } else {
  494. remote.add(filePath);
  495. local.add(data);
  496. }
  497. }
  498. else {
  499. throw new SecurityException();
  500. }
  501. Intent intent = new Intent(getApplicationContext(), FileUploader.class);
  502. intent.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_MULTIPLE_FILES);
  503. intent.putExtra(FileUploader.KEY_LOCAL_FILE, local.toArray(new String[local.size()]));
  504. intent.putExtra(FileUploader.KEY_REMOTE_FILE,
  505. remote.toArray(new String[remote.size()]));
  506. intent.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
  507. startService(intent);
  508. //Save the path to shared preferences
  509. SharedPreferences.Editor appPrefs = PreferenceManager
  510. .getDefaultSharedPreferences(getApplicationContext()).edit();
  511. appPrefs.putString("last_upload_path", mUploadPath);
  512. appPrefs.apply();
  513. finish();
  514. }
  515. } catch (SecurityException e) {
  516. String message = String.format(getString(R.string.uploader_error_forbidden_content),
  517. getString(R.string.app_name));
  518. Toast.makeText(this, message, Toast.LENGTH_LONG).show();
  519. }
  520. }
  521. @Override
  522. public void onRemoteOperationFinish(RemoteOperation operation, RemoteOperationResult result) {
  523. super.onRemoteOperationFinish(operation, result);
  524. if (operation instanceof CreateFolderOperation) {
  525. onCreateFolderOperationFinish((CreateFolderOperation)operation, result);
  526. }
  527. }
  528. /**
  529. * Updates the view associated to the activity after the finish of an operation
  530. * trying create a new folder
  531. *
  532. * @param operation Creation operation performed.
  533. * @param result Result of the creation.
  534. */
  535. private void onCreateFolderOperationFinish(CreateFolderOperation operation,
  536. RemoteOperationResult result) {
  537. if (result.isSuccess()) {
  538. populateDirectoryList();
  539. } else {
  540. try {
  541. Toast msg = Toast.makeText(this,
  542. ErrorMessageAdapter.getErrorCauseMessage(result, operation, getResources()),
  543. Toast.LENGTH_LONG);
  544. msg.show();
  545. } catch (NotFoundException e) {
  546. Log_OC.e(TAG, "Error while trying to show fail message " , e);
  547. }
  548. }
  549. }
  550. /**
  551. * Loads the target folder initialize shown to the user.
  552. *
  553. * The target account has to be chosen before this method is called.
  554. */
  555. private void initTargetFolder() {
  556. if (getStorageManager() == null) {
  557. throw new IllegalStateException("Do not call this method before " +
  558. "initializing mStorageManager");
  559. }
  560. SharedPreferences appPreferences = PreferenceManager
  561. .getDefaultSharedPreferences(getApplicationContext());
  562. String last_path = appPreferences.getString("last_upload_path", "");
  563. // "/" equals root-directory
  564. if(last_path.equals("/")) {
  565. mParents.add("");
  566. } else{
  567. String[] dir_names = last_path.split("/");
  568. mParents.clear();
  569. for (String dir : dir_names)
  570. mParents.add(dir);
  571. }
  572. //Make sure that path still exists, if it doesn't pop the stack and try the previous path
  573. while(!getStorageManager().fileExists(generatePath(mParents)) && mParents.size() > 1){
  574. mParents.pop();
  575. }
  576. }
  577. @Override
  578. public boolean onCreateOptionsMenu(Menu menu) {
  579. MenuInflater inflater = getMenuInflater();
  580. inflater.inflate(R.menu.main_menu, menu);
  581. menu.findItem(R.id.action_upload).setVisible(false);
  582. menu.findItem(R.id.action_sort).setVisible(false);
  583. menu.findItem(R.id.action_sync_account).setVisible(false);
  584. return true;
  585. }
  586. @Override
  587. public boolean onOptionsItemSelected(MenuItem item) {
  588. boolean retval = true;
  589. switch (item.getItemId()) {
  590. case R.id.action_create_dir:
  591. CreateFolderDialogFragment dialog = CreateFolderDialogFragment.newInstance(mFile);
  592. dialog.show(
  593. getSupportFragmentManager(),
  594. CreateFolderDialogFragment.CREATE_FOLDER_FRAGMENT);
  595. break;
  596. case android.R.id.home:
  597. if((mParents.size() > 1)) {
  598. onBackPressed();
  599. }
  600. break;
  601. default:
  602. retval = super.onOptionsItemSelected(item);
  603. }
  604. return retval;
  605. }
  606. /**
  607. * Process the result of CopyTmpFileAsyncTask
  608. * @param result
  609. * @param index
  610. */
  611. @Override
  612. public void onTmpFileCopied(String result, int index) {
  613. if (mNumCacheFile -- == 0) {
  614. dismissWaitingCopyDialog();
  615. }
  616. if (result != null) {
  617. Intent intent = new Intent(getApplicationContext(), FileUploader.class);
  618. intent.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
  619. intent.putExtra(FileUploader.KEY_LOCAL_FILE, result);
  620. intent.putExtra(FileUploader.KEY_REMOTE_FILE, mRemoteCacheData.get(index));
  621. intent.putExtra(FileUploader.KEY_ACCOUNT, getAccount());
  622. startService(intent);
  623. } else {
  624. String message = String.format(getString(R.string.uploader_error_forbidden_content),
  625. getString(R.string.app_name));
  626. Toast.makeText(this, message, Toast.LENGTH_LONG).show();
  627. Log_OC.d(TAG, message);
  628. }
  629. }
  630. /**
  631. * Show waiting for copy dialog
  632. */
  633. public void showWaitingCopyDialog() {
  634. // Construct dialog
  635. LoadingDialog loading = new LoadingDialog(
  636. getResources().getString(R.string.wait_for_tmp_copy_from_private_storage));
  637. FragmentManager fm = getSupportFragmentManager();
  638. FragmentTransaction ft = fm.beginTransaction();
  639. loading.show(ft, DIALOG_WAIT_COPY_FILE);
  640. }
  641. /**
  642. * Dismiss waiting for copy dialog
  643. */
  644. public void dismissWaitingCopyDialog(){
  645. Fragment frag = getSupportFragmentManager().findFragmentByTag(DIALOG_WAIT_COPY_FILE);
  646. if (frag != null) {
  647. LoadingDialog loading = (LoadingDialog) frag;
  648. loading.dismiss();
  649. }
  650. }
  651. }