Filter broadcast messages in receivers with the account, to avoid problems with servi...
[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 @Override
65 public void onCreate() {
66 super.onCreate();
67 mNotificationMngr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
68 HandlerThread thread = new HandlerThread("FileDownladerThread",
69 Process.THREAD_PRIORITY_BACKGROUND);
70 thread.start();
71 mServiceLooper = thread.getLooper();
72 mServiceHandler = new ServiceHandler(mServiceLooper);
73 }
74
75 @Override
76 public IBinder onBind(Intent arg0) {
77 return null;
78 }
79
80 @Override
81 public int onStartCommand(Intent intent, int flags, int startId) {
82 if (!intent.hasExtra(EXTRA_ACCOUNT)
83 && !intent.hasExtra(EXTRA_FILE_PATH)) {
84 Log.e(TAG, "Not enough information provided in intent");
85 return START_STICKY;
86 }
87 mAccount = intent.getParcelableExtra(EXTRA_ACCOUNT);
88 mFilePath = intent.getStringExtra(EXTRA_FILE_PATH);
89 mRemotePath = intent.getStringExtra(EXTRA_REMOTE_PATH);
90 Message msg = mServiceHandler.obtainMessage();
91 msg.arg1 = startId;
92 mServiceHandler.sendMessage(msg);
93 mCurrentDownlodSize = mLastPercent = 0;
94 mTotalDownloadSize = intent.getLongExtra(EXTRA_FILE_SIZE, -1);
95
96 return START_NOT_STICKY;
97 }
98
99 void downloadFile() {
100 AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
101
102
103 WebdavClient wdc = new WebdavClient(mAccount, getApplicationContext());
104
105 String username = mAccount.name.split("@")[0];
106 String password = "";
107 try {
108 password = am.blockingGetAuthToken(mAccount,
109 AccountAuthenticator.AUTH_TOKEN_TYPE, true);
110 } catch (Exception e) {
111 e.printStackTrace();
112 return;
113 }
114
115 wdc.setCredentials(username, password);
116 wdc.allowSelfsignedCertificates();
117 wdc.setDataTransferProgressListener(this);
118
119 mNotification = new Notification(R.drawable.icon, "Downloading file", System.currentTimeMillis());
120
121 mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
122 mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);
123 mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, mTotalDownloadSize == -1);
124 mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);
125 // dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
126 // 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
127 mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
128
129 mNotificationMngr.notify(1, mNotification);
130
131 File sdCard = Environment.getExternalStorageDirectory();
132 File file = new File(sdCard.getAbsolutePath() + "/owncloud/" + mAccount.name + mFilePath);
133 file.getParentFile().mkdirs();
134
135 boolean download_result = false;
136 if (wdc.downloadFile(mRemotePath, file)) {
137 ContentValues cv = new ContentValues();
138 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getAbsolutePath());
139 getContentResolver().update(
140 ProviderTableMeta.CONTENT_URI,
141 cv,
142 ProviderTableMeta.FILE_NAME + "=? AND "
143 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
144 new String[] {
145 mFilePath.substring(mFilePath.lastIndexOf('/') + 1),
146 mAccount.name });
147 download_result = true;
148 }
149
150 mNotificationMngr.cancel(1);
151 Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
152 end.putExtra(EXTRA_REMOTE_PATH, mRemotePath);
153 end.putExtra(EXTRA_FILE_PATH, file.getAbsolutePath());
154 end.putExtra(EXTRA_DOWNLOAD_RESULT, download_result);
155 end.putExtra(ACCOUNT_NAME, mAccount.name);
156 sendBroadcast(end);
157
158 if (download_result) {
159 Toast.makeText(this, R.string.downloader_download_succeed , Toast.LENGTH_SHORT).show();
160 } else {
161 Toast.makeText(this, R.string.downloader_download_failed , Toast.LENGTH_SHORT).show();
162 }
163
164 }
165
166 @Override
167 public void transferProgress(long progressRate) {
168 mCurrentDownlodSize += progressRate;
169 int percent = (int)(100.0*((double)mCurrentDownlodSize)/((double)mTotalDownloadSize));
170 if (percent != mLastPercent) {
171 mNotification.contentView.setProgressBar(R.id.status_progress, 100, (int)(100*mCurrentDownlodSize/mTotalDownloadSize), mTotalDownloadSize == -1);
172 mNotification.contentView.setTextViewText(R.id.status_text, percent+"%");
173 mNotificationMngr.notify(1, mNotification);
174 }
175
176 mLastPercent = percent;
177 }
178
179
180 }