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