Uploader.java 29 KB

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