cb5d0c8d43965257a66baaf1f54933f03ba01d64
[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.owncloud.syncadapter.FileSyncService;
29 import eu.alefzero.webdav.WebdavClient;
30
31 public class FileDownloader extends Service implements OnDatatransferProgressListener {
32 public static final String DOWNLOAD_FINISH_MESSAGE = "DOWNLOAD_FINISH";
33 public static final String EXTRA_DOWNLOAD_RESULT = "RESULT";
34 public static final String EXTRA_ACCOUNT = "ACCOUNT";
35 public static final String EXTRA_FILE_PATH = "FILE_PATH";
36 public static final String EXTRA_REMOTE_PATH = "REMOTE_PATH";
37 public static final String EXTRA_FILE_SIZE = "FILE_SIZE";
38 public static final String ACCOUNT_NAME = "ACCOUNT_NAME";
39 private static final String TAG = "FileDownloader";
40
41 private NotificationManager mNotificationMngr;
42 private Looper mServiceLooper;
43 private ServiceHandler mServiceHandler;
44 private Account mAccount;
45 private String mFilePath;
46 private String mRemotePath;
47 private int mLastPercent;
48 private long mTotalDownloadSize;
49 private long mCurrentDownlodSize;
50 private Notification mNotification;
51
52 private final class ServiceHandler extends Handler {
53 public ServiceHandler(Looper looper) {
54 super(looper);
55 }
56
57 @Override
58 public void handleMessage(Message msg) {
59 downloadFile();
60 stopSelf(msg.arg1);
61 }
62 }
63
64 public static final String getSavePath() {
65 File sdCard = Environment.getExternalStorageDirectory();
66 return sdCard.getAbsolutePath() + "/owncloud/";
67 }
68
69 public static final String getTemporalPath() {
70 File sdCard = Environment.getExternalStorageDirectory();
71 return sdCard.getAbsolutePath() + "/owncloud.tmp/";
72 }
73
74 @Override
75 public void onCreate() {
76 super.onCreate();
77 mNotificationMngr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
78 HandlerThread thread = new HandlerThread("FileDownladerThread",
79 Process.THREAD_PRIORITY_BACKGROUND);
80 thread.start();
81 mServiceLooper = thread.getLooper();
82 mServiceHandler = new ServiceHandler(mServiceLooper);
83 }
84
85 @Override
86 public IBinder onBind(Intent arg0) {
87 return null;
88 }
89
90 @Override
91 public int onStartCommand(Intent intent, int flags, int startId) {
92 if (!intent.hasExtra(EXTRA_ACCOUNT)
93 && !intent.hasExtra(EXTRA_FILE_PATH)) {
94 Log.e(TAG, "Not enough information provided in intent");
95 return START_STICKY;
96 }
97 mAccount = intent.getParcelableExtra(EXTRA_ACCOUNT);
98 mFilePath = intent.getStringExtra(EXTRA_FILE_PATH);
99 mRemotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
100 Message msg = mServiceHandler.obtainMessage();
101 msg.arg1 = startId;
102 mServiceHandler.sendMessage(msg);
103 mCurrentDownlodSize = mLastPercent = 0;
104 mTotalDownloadSize = intent.getLongExtra(EXTRA_FILE_SIZE, -1);
105
106 return START_NOT_STICKY;
107 }
108
109 void downloadFile() {
110 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
111
112
113 WebdavClient wdc = new WebdavClient(mAccount, getApplicationContext());
114
115 String username = mAccount.name.split("@")[0];
116 String password = "";
117 try {
118 password = am.blockingGetAuthToken(mAccount,
119 AccountAuthenticator.AUTH_TOKEN_TYPE, true);
120 } catch (Exception e) {
121 e.printStackTrace();
122 return;
123 }
124
125 wdc.setCredentials(username, password);
126 wdc.allowSelfsignedCertificates();
127 wdc.setDataTransferProgressListener(this);
128
129 mNotification = new Notification(R.drawable.icon, "Downloading file", System.currentTimeMillis());
130
131 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
132 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
133 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, mTotalDownloadSize == -1);
134 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
135 // dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
136 // 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
137 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
138
139 mNotificationMngr.notify(1, mNotification);
140
141 // download in a temporal file
142 File tmpFile = new File(getTemporalPath() + mAccount.name + mFilePath);
143 tmpFile.getParentFile().mkdirs();
144
145 boolean download_result = false;
146 File newFile = null;
147 if (wdc.downloadFile(mRemotePath, tmpFile)) {
148 newFile = new File(getSavePath() + mAccount.name + mFilePath);
149 newFile.getParentFile().mkdirs();
150 boolean moved = tmpFile.renameTo(newFile);
151
152 if (moved) {
153 ContentValues cv = new ContentValues();
154 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, newFile.getAbsolutePath());
155 getContentResolver().update(
156 ProviderTableMeta.CONTENT_URI,
157 cv,
158 ProviderTableMeta.FILE_NAME + "=? AND "
159 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
160 new String[] {
161 mFilePath.substring(mFilePath.lastIndexOf('/') + 1),
162 mAccount.name });
163 download_result = true;
164 }
165 }
166
167 if (!download_result) {
168 tmpFile.delete();
169 }
170
171 mNotificationMngr.cancel(1);
172 Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
173 end.putExtra(EXTRA_REMOTE_PATH, mRemotePath);
174 end.putExtra(EXTRA_FILE_PATH, newFile.getAbsolutePath());
175 end.putExtra(EXTRA_DOWNLOAD_RESULT, download_result);
176 end.putExtra(ACCOUNT_NAME, mAccount.name);
177 sendBroadcast(end);
178
179 if (download_result) {
180 Toast.makeText(this, R.string.downloader_download_succeed , Toast.LENGTH_SHORT).show();
181 } else {
182 Toast.makeText(this, R.string.downloader_download_failed , Toast.LENGTH_SHORT).show();
183 }
184
185 }
186
187 @Override
188 public void transferProgress(long progressRate) {
189 mCurrentDownlodSize += progressRate;
190 int percent = (int)(100.0*((double)mCurrentDownlodSize)/((double)mTotalDownloadSize));
191 if (percent != mLastPercent) {
192 mNotification.contentView.setProgressBar(R.id.status_progress, 100, (int)(100*mCurrentDownlodSize/mTotalDownloadSize), mTotalDownloadSize == -1);
193 mNotification.contentView.setTextViewText(R.id.status_text, percent+"%");
194 mNotificationMngr.notify(1, mNotification);
195 }
196
197 mLastPercent = percent;
198 }
199
200
201 }