cc66e3826036b2366e1f517621c832f49c649058
[pub/Android/ownCloud.git] / src / eu / alefzero / owncloud / files / services / FileDownloader.java
1 package eu.alefzero.owncloud.files.services;
2
3 import java.io.File;
4 import java.io.IOException;
5
6 import android.accounts.Account;
7 import android.accounts.AccountManager;
8 import android.app.Notification;
9 import android.app.NotificationManager;
10 import android.app.PendingIntent;
11 import android.app.Service;
12 import android.content.ContentValues;
13 import android.content.Intent;
14 import android.os.Environment;
15 import android.os.Handler;
16 import android.os.HandlerThread;
17 import android.os.IBinder;
18 import android.os.Looper;
19 import android.os.Message;
20 import android.os.Process;
21 import android.util.Log;
22 import android.widget.RemoteViews;
23 import android.widget.Toast;
24 import eu.alefzero.owncloud.R;
25 import eu.alefzero.owncloud.authenticator.AccountAuthenticator;
26 import eu.alefzero.owncloud.db.ProviderMeta.ProviderTableMeta;
27 import eu.alefzero.owncloud.files.interfaces.OnDatatransferProgressListener;
28 import eu.alefzero.webdav.WebdavClient;
29
30 public class FileDownloader extends Service implements OnDatatransferProgressListener {
31 public static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
32 public static final String EXTRA_DOWNLOAD_RESULT = "RESULT";
33 public static final String EXTRA_ACCOUNT = "ACCOUNT";
34 public static final String EXTRA_FILE_PATH = "FILE_PATH";
35 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
36 public static final String EXTRA_FILE_SIZE = "FILE_SIZE";
37 private static final String TAG = "FileDownloader";
38
39 private NotificationManager mNotificationMngr;
40 private Looper mServiceLooper;
41 private ServiceHandler mServiceHandler;
42 private Account mAccount;
43 private String mFilePath;
44 private String mRemotePath;
45 private int mLastPercent;
46 private long mTotalDownloadSize;
47 private long mCurrentDownlodSize;
48 private Notification mNotification;
49
50 private final class ServiceHandler extends Handler {
51 public ServiceHandler(Looper looper) {
52 super(looper);
53 }
54
55 @Override
56 public void handleMessage(Message msg) {
57 downloadFile();
58 stopSelf(msg.arg1);
59 }
60 }
61
62 @Override
63 public void onCreate() {
64 super.onCreate();
65 mNotificationMngr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
66 HandlerThread thread = new HandlerThread("FileDownladerThread",
67 Process.THREAD_PRIORITY_BACKGROUND);
68 thread.start();
69 mServiceLooper = thread.getLooper();
70 mServiceHandler = new ServiceHandler(mServiceLooper);
71 }
72
73 @Override
74 public IBinder onBind(Intent arg0) {
75 return null;
76 }
77
78 @Override
79 public int onStartCommand(Intent intent, int flags, int startId) {
80 if (!intent.hasExtra(EXTRA_ACCOUNT)
81 && !intent.hasExtra(EXTRA_FILE_PATH)) {
82 Log.e(TAG, "Not enough information provided in intent");
83 return START_STICKY;
84 }
85 mAccount = intent.getParcelableExtra(EXTRA_ACCOUNT);
86 mFilePath = intent.getStringExtra(EXTRA_FILE_PATH);
87 mRemotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
88 Message msg = mServiceHandler.obtainMessage();
89 msg.arg1 = startId;
90 mServiceHandler.sendMessage(msg);
91 mCurrentDownlodSize = mLastPercent = 0;
92 mTotalDownloadSize = intent.getLongExtra(EXTRA_FILE_SIZE, -1);
93
94 return START_NOT_STICKY;
95 }
96
97 void downloadFile() {
98 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
99
100
101 WebdavClient wdc = new WebdavClient(mAccount, getApplicationContext());
102
103 String username = mAccount.name.split("@")[0];
104 String password = "";
105 try {
106 password = am.blockingGetAuthToken(mAccount,
107 AccountAuthenticator.AUTH_TOKEN_TYPE, true);
108 } catch (Exception e) {
109 e.printStackTrace();
110 return;
111 }
112
113 wdc.setCredentials(username, password);
114 wdc.allowSelfsignedCertificates();
115 wdc.setDataTransferProgressListener(this);
116
117 mNotification = new Notification(R.drawable.icon, "Downloading file", System.currentTimeMillis());
118
119 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
120 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
121 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, mTotalDownloadSize == -1);
122 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
123 // dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
124 // BUT an empty Intent is not a very elegant solution; something smart should happen when a user 'clicks' on a download in the notification bar
125 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
126
127 mNotificationMngr.notify(1, mNotification);
128
129 File sdCard = Environment.getExternalStorageDirectory();
130 File file = new File(sdCard.getAbsolutePath() + "/owncloud/" + mAccount.name + mFilePath);
131 file.getParentFile().mkdirs();
132
133 boolean download_result = false;
134 if (wdc.downloadFile(mRemotePath, file)) {
135 ContentValues cv = new ContentValues();
136 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getAbsolutePath());
137 getContentResolver().update(
138 ProviderTableMeta.CONTENT_URI,
139 cv,
140 ProviderTableMeta.FILE_NAME + "=? AND "
141 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
142 new String[] {
143 mFilePath.substring(mFilePath.lastIndexOf('/') + 1),
144 mAccount.name });
145 download_result = true;
146 }
147
148 mNotificationMngr.cancel(1);
149 Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
150 end.putExtra(EXTRA_REMOTE_PATH, mRemotePath);
151 end.putExtra(EXTRA_FILE_PATH, file.getAbsolutePath());
152 end.putExtra(EXTRA_DOWNLOAD_RESULT, download_result);
153 sendBroadcast(end);
154
155 if (download_result) {
156 Toast.makeText(this, R.string.downloader_download_succeed , Toast.LENGTH_SHORT).show();
157 } else {
158 Toast.makeText(this, R.string.downloader_download_failed , Toast.LENGTH_SHORT).show();
159 }
160
161 }
162
163 @Override
164 public void transferProgress(long progressRate) {
165 mCurrentDownlodSize += progressRate;
166 int percent = (int)(100.0*((double)mCurrentDownlodSize)/((double)mTotalDownloadSize));
167 if (percent != mLastPercent) {
168 mNotification.contentView.setProgressBar(R.id.status_progress, 100, (int)(100*mCurrentDownlodSize/mTotalDownloadSize), mTotalDownloadSize == -1);
169 mNotification.contentView.setTextViewText(R.id.status_text, percent+"%");
170 mNotificationMngr.notify(1, mNotification);
171 }
172
173 mLastPercent = percent;
174 }
175
176
177 }