new icons, new uploader
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / ui / activity / FileDisplayActivity.java
1 /* ownCloud Android client application
2 * Copyright (C) 2011 Bartek Przybylski
3 *
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
16 *
17 */
18
19 package eu.alefzero.owncloud.ui.activity;
20
21 import java.io.File;
22 import java.net.URLEncoder;
23
24 import android.accounts.Account;
25 import android.accounts.AccountManager;
26 import android.app.AlertDialog;
27 import android.app.AlertDialog.Builder;
28 import android.app.Dialog;
29 import android.content.BroadcastReceiver;
30 import android.content.ContentResolver;
31 import android.content.Context;
32 import android.content.DialogInterface;
33 import android.content.DialogInterface.OnClickListener;
34 import android.content.Intent;
35 import android.content.IntentFilter;
36 import android.database.Cursor;
37 import android.net.Uri;
38 import android.os.Bundle;
39 import android.provider.MediaStore;
40 import android.util.Log;
41 import android.view.View;
42 import android.view.ViewGroup;
43 import android.widget.ArrayAdapter;
44 import android.widget.EditText;
45 import android.widget.TextView;
46
47 import com.actionbarsherlock.app.ActionBar;
48 import com.actionbarsherlock.app.ActionBar.OnNavigationListener;
49 import com.actionbarsherlock.app.SherlockFragmentActivity;
50 import com.actionbarsherlock.view.Menu;
51 import com.actionbarsherlock.view.MenuInflater;
52 import com.actionbarsherlock.view.MenuItem;
53 import com.actionbarsherlock.view.Window;
54
55 import eu.alefzero.owncloud.AccountUtils;
56 import eu.alefzero.owncloud.R;
57 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
58 import eu.alefzero.owncloud.datamodel.DataStorageManager;
59 import eu.alefzero.owncloud.datamodel.FileDataStorageManager;
60 import eu.alefzero.owncloud.datamodel.OCFile;
61 import eu.alefzero.owncloud.files.services.FileUploader;
62 import eu.alefzero.owncloud.syncadapter.FileSyncService;
63 import eu.alefzero.owncloud.ui.fragment.FileListFragment;
64 import eu.alefzero.owncloud.utils.OwnCloudVersion;
65 import eu.alefzero.webdav.WebdavClient;
66
67 /**
68 * Displays, what files the user has available in his ownCloud.
69 *
70 * @author Bartek Przybylski
71 *
72 */
73
74 public class FileDisplayActivity extends SherlockFragmentActivity implements
75 OnNavigationListener, OnClickListener {
76 private ArrayAdapter<String> mDirectories;
77 private DataStorageManager mStorageManager;
78
79 private SyncBroadcastReceiver syncBroadcastRevceiver;
80
81 private static final int DIALOG_SETUP_ACCOUNT = 0;
82 private static final int DIALOG_CREATE_DIR = 1;
83
84 private static final int REQUEST_ACCOUNT_SETUP = 0;
85 private static final int ACTION_SELECT_FILE = 1;
86
87 public void pushPath(String path) {
88 mDirectories.insert(path, 0);
89 }
90
91 public boolean popPath() {
92 mDirectories.remove(mDirectories.getItem(0));
93 return !mDirectories.isEmpty();
94 }
95
96 @Override
97 protected Dialog onCreateDialog(int id) {
98 Dialog dialog;
99 AlertDialog.Builder builder;
100 switch(id){
101 case DIALOG_SETUP_ACCOUNT:
102 builder = new AlertDialog.Builder(this);
103 builder.setTitle(R.string.main_tit_accsetup);
104 builder.setMessage(R.string.main_wrn_accsetup);
105 builder.setCancelable(false);
106 builder.setPositiveButton(android.R.string.ok, this);
107 builder.setNegativeButton(android.R.string.cancel, this);
108 dialog = builder.create();
109 break;
110 case DIALOG_CREATE_DIR:
111 {
112 builder = new Builder(this);
113 final EditText dirName = new EditText(getBaseContext());
114 final Account a = AccountUtils.getCurrentOwnCloudAccount(this);
115 builder.setView(dirName);
116 builder.setTitle(R.string.uploader_info_dirname);
117 int typed_color = getResources().getColor(R.color.setup_text_typed);
118 dirName.setTextColor(typed_color);
119
120 builder.setPositiveButton(android.R.string.ok, new OnClickListener() {
121 public void onClick(DialogInterface dialog, int which) {
122 String s = dirName.getText().toString();
123 if (s.trim().length() == 0) {
124 dialog.cancel();
125 return;
126 }
127
128 String path = "";
129 for (int i = mDirectories.getCount() - 2; i >= 0; --i) {
130 path += "/" + mDirectories.getItem(i);
131 }
132 OCFile parent = mStorageManager.getFileByPath(path + "/");
133 path += s + "/";
134 Thread thread = new Thread(new DirectoryCreator(path, a));
135 thread.start();
136
137 OCFile new_file = new OCFile(path);
138 new_file.setMimetype("DIR");
139 new_file.setParentId(parent.getParentId());
140 mStorageManager.saveFile(new_file);
141
142 dialog.dismiss();
143 }
144 });
145 builder.setNegativeButton(R.string.common_cancel,
146 new OnClickListener() {
147 public void onClick(DialogInterface dialog, int which) {
148 dialog.cancel();
149 }
150 });
151 dialog = builder.create();
152 break;
153 }
154 default:
155 dialog = null;
156 }
157
158 return dialog;
159 }
160
161 @Override
162 public void onCreate(Bundle savedInstanceState) {
163 super.onCreate(savedInstanceState);
164
165 if(!accountsAreSetup()){
166 showDialog(DIALOG_SETUP_ACCOUNT);
167 return;
168 }
169
170 requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
171 setProgressBarIndeterminateVisibility(false);
172 //if (getSupportFragmentManager().findFragmentById(R.id.fileList) == null)
173 setContentView(R.layout.files);
174
175 }
176
177 @Override
178 public boolean onOptionsItemSelected(MenuItem item) {
179 boolean retval = true;
180 switch (item.getItemId()) {
181 case R.id.settingsItem: {
182 Intent i = new Intent(this, Preferences.class);
183 startActivity(i);
184 break;
185 }
186 case R.id.createDirectoryItem: {
187 showDialog(DIALOG_CREATE_DIR);
188 break;
189 }
190 case R.id.startSync: {
191 Bundle bundle = new Bundle();
192 bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
193 ContentResolver.requestSync(AccountUtils.getCurrentOwnCloudAccount(this),
194 "org.owncloud",
195 bundle);
196 break;
197 }
198 case R.id.action_upload: {
199 Intent action = new Intent(Intent.ACTION_GET_CONTENT);
200 action = action.setType("*/*").addCategory(Intent.CATEGORY_OPENABLE);
201 startActivityForResult(Intent.createChooser(action, "Upload file from..."), ACTION_SELECT_FILE);
202 break;
203 }
204
205 case android.R.id.home: {
206 Intent i = new Intent(this, AccountSelectActivity.class);
207 startActivity(i);
208 finish();
209 break;
210 }
211 default:
212 retval = false;
213 }
214 return retval;
215 }
216
217 @Override
218 public void onBackPressed(){
219 if(mDirectories.getCount() == 1) {
220 finish();
221 return;
222 }
223 popPath();
224 ((FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList))
225 .onNavigateUp();
226 }
227
228 @Override
229 public boolean onCreateOptionsMenu(Menu menu) {
230 MenuInflater inflater = getSherlock().getMenuInflater();
231 inflater.inflate(R.menu.menu, menu);
232 return true;
233 }
234
235 @Override
236 protected void onRestoreInstanceState(Bundle savedInstanceState) {
237 super.onRestoreInstanceState(savedInstanceState);
238 // Check, if there are ownCloud accounts
239 if(!accountsAreSetup()){
240 showDialog(DIALOG_SETUP_ACCOUNT);
241 }
242 }
243
244
245 @Override
246 protected void onResume() {
247 super.onResume();
248 if(!accountsAreSetup()){
249 showDialog(DIALOG_SETUP_ACCOUNT);
250 return;
251 }
252
253 IntentFilter f = new IntentFilter(FileSyncService.SYNC_MESSAGE);
254 syncBroadcastRevceiver = new SyncBroadcastReceiver();
255 registerReceiver(syncBroadcastRevceiver, f);
256
257 mDirectories = new CustomArrayAdapter<String>(this,
258 R.layout.sherlock_spinner_dropdown_item);
259 mDirectories.add("/");
260
261 mStorageManager = new FileDataStorageManager(AccountUtils.getCurrentOwnCloudAccount(this), getContentResolver());
262 ActionBar action_bar = getSupportActionBar();
263 action_bar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
264 action_bar.setDisplayShowTitleEnabled(false);
265 action_bar.setListNavigationCallbacks(mDirectories, this);
266 action_bar.setDisplayHomeAsUpEnabled(true);
267 }
268
269 public void onActivityResult(int requestCode, int resultCode, Intent data) {
270 Log.e("ASD", requestCode + " " + resultCode);
271 if (resultCode == RESULT_OK) {
272 if (requestCode == ACTION_SELECT_FILE) {
273 Uri selectedImageUri = data.getData();
274
275 String filemanagerstring = selectedImageUri.getPath();
276 String selectedImagePath = getPath(selectedImageUri);
277 String filepath;
278
279 if(selectedImagePath!=null)
280 filepath = selectedImagePath;
281 else
282 filepath = filemanagerstring;
283
284 if (filepath == null) {
285 Log.e("FileDisplay", "Couldnt resolve path to file");
286 return;
287 }
288
289 Intent i = new Intent(this, FileUploader.class);
290 i.putExtra(FileUploader.KEY_ACCOUNT, AccountUtils.getCurrentOwnCloudAccount(this));
291 String remotepath = new String();
292 for (int j = mDirectories.getCount() - 2; j >= 0; --j) {
293 remotepath += "/" + mDirectories.getItem(j);
294 }
295 if (!remotepath.endsWith("/")) remotepath += "/";
296 remotepath += new File(filepath).getName();
297 Log.e("ASD", remotepath+"");
298
299 i.putExtra(FileUploader.KEY_LOCAL_FILE, filepath);
300 i.putExtra(FileUploader.KEY_REMOTE_FILE, remotepath);
301 i.putExtra(FileUploader.KEY_UPLOAD_TYPE, FileUploader.UPLOAD_SINGLE_FILE);
302 startService(i);
303 }
304 }
305 }
306
307 public String getPath(Uri uri) {
308 String[] projection = { MediaStore.Images.Media.DATA };
309 Cursor cursor = managedQuery(uri, projection, null, null, null);
310 if(cursor!=null)
311 {
312 int column_index = cursor
313 .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
314 cursor.moveToFirst();
315 return cursor.getString(column_index);
316 }
317 else return null;
318 }
319
320 @Override
321 protected void onPause() {
322 super.onPause();
323 if (syncBroadcastRevceiver != null) {
324 unregisterReceiver(syncBroadcastRevceiver);
325 syncBroadcastRevceiver = null;
326 }
327
328 }
329
330 @Override
331 public boolean onNavigationItemSelected(int itemPosition, long itemId) {
332 int i = itemPosition;
333 while (i-- != 0) {
334 onBackPressed();
335 }
336 return true;
337 }
338
339 private class DirectoryCreator implements Runnable {
340 private String mTargetPath;
341 private Account mAccount;
342 private AccountManager mAm;
343
344 public DirectoryCreator(String targetPath, Account account) {
345 mTargetPath = targetPath;
346 mAccount = account;
347 mAm = (AccountManager) getSystemService(ACCOUNT_SERVICE);
348 }
349
350 @Override
351 public void run() {
352 WebdavClient wdc = new WebdavClient(Uri.parse(mAm.getUserData(
353 mAccount, AccountAuthenticator.KEY_OC_URL)));
354
355 String username = mAccount.name.substring(0,
356 mAccount.name.lastIndexOf('@'));
357 String password = mAm.getPassword(mAccount);
358
359 wdc.setCredentials(username, password);
360 wdc.allowUnsignedCertificates();
361 wdc.createDirectory(mTargetPath);
362 }
363
364 }
365
366 // Custom array adapter to override text colors
367 private class CustomArrayAdapter<T> extends ArrayAdapter<T> {
368
369 public CustomArrayAdapter(FileDisplayActivity ctx,
370 int view) {
371 super(ctx, view);
372 }
373
374 public View getView(int position, View convertView,
375 ViewGroup parent) {
376 View v = super.getView(position, convertView, parent);
377
378 ((TextView) v).setTextColor(
379 getResources()
380 .getColorStateList(android.R.color.white));
381 return v;
382 }
383
384 public View getDropDownView(int position, View convertView,
385 ViewGroup parent) {
386 View v = super.getDropDownView(position, convertView,
387 parent);
388
389 ((TextView) v).setTextColor(getResources().getColorStateList(
390 android.R.color.white));
391
392 return v;
393 }
394
395
396
397 }
398
399 public void onClick(DialogInterface dialog, int which) {
400 // In any case - we won't need it anymore
401 dialog.dismiss();
402 switch(which){
403 case DialogInterface.BUTTON_POSITIVE:
404 Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
405 intent.putExtra("authorities",
406 new String[] { AccountAuthenticator.AUTH_TOKEN_TYPE });
407 startActivity(intent);
408 break;
409 case DialogInterface.BUTTON_NEGATIVE:
410 finish();
411 }
412
413 }
414
415 /**
416 * Checks, whether or not there are any ownCloud accounts
417 * setup.
418 *
419 * @return true, if there is at least one account.
420 */
421 private boolean accountsAreSetup() {
422 AccountManager accMan = AccountManager.get(this);
423 Account[] accounts = accMan
424 .getAccountsByType(AccountAuthenticator.ACCOUNT_TYPE);
425 return accounts.length > 0;
426 }
427
428 private class SyncBroadcastReceiver extends BroadcastReceiver {
429 /**
430 * {@link BroadcastReceiver} to enable syncing feedback in UI
431 */
432 @Override
433 public void onReceive(Context context, Intent intent) {
434 boolean inProgress = intent.getBooleanExtra(FileSyncService.IN_PROGRESS, false);
435 String account_name = intent.getStringExtra(FileSyncService.ACCOUNT_NAME);
436 Log.d("FileDisplay", "sync of account " + account_name + " is in_progress: " + inProgress);
437 setProgressBarIndeterminateVisibility(inProgress);
438 if (!inProgress) {
439 FileListFragment fileListFramgent = (FileListFragment) getSupportFragmentManager().findFragmentById(R.id.fileList);
440 if (fileListFramgent != null)
441 fileListFramgent.populateFileList();
442 }
443 }
444
445 }
446
447 }