9c9b3eff81c0b347e54db053f19af05af6e17ce4
[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 EXTRA_DOWNLOAD_RESULT = "RESULT";
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 file.getParentFile().mkdirs();
131
132 boolean download_result = false;
133 if (wdc.downloadFile(mRemotePath, file)) {
134 ContentValues cv = new ContentValues();
135 cv.put(ProviderTableMeta.FILE_STORAGE_PATH, file.getAbsolutePath());
136 getContentResolver().update(
137 ProviderTableMeta.CONTENT_URI,
138 cv,
139 ProviderTableMeta.FILE_NAME + "=? AND "
140 + ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?",
141 new String[] {
142 mFilePath.substring(mFilePath.lastIndexOf('/') + 1),
143 mAccount.name });
144 download_result = true;
145 }
146
147 mNotificationMngr.cancel(1);
148 Intent end = new Intent(DOWNLOAD_FINISH_MESSAGE);
149 end.putExtra(EXTRA_FILE_PATH, file.getAbsolutePath());
150 end.putExtra(EXTRA_DOWNLOAD_RESULT, download_result);
151 sendBroadcast(end);
152 }
153
154 @Override
155 public void transferProgress(long progressRate) {
156 mCurrentDownlodSize += progressRate;
157 int percent = (int)(100.0*((double)mCurrentDownlodSize)/((double)mTotalDownloadSize));
158 if (percent != mLastPercent) {
159 mNotification.contentView.setProgressBar(R.id.status_progress, 100, (int)(100*mCurrentDownlodSize/mTotalDownloadSize), mTotalDownloadSize == -1);
160 mNotification.contentView.setTextViewText(R.id.status_text, percent+"%");
161 mNotificationMngr.notify(1, mNotification);
162 }
163
164 mLastPercent = percent;
165 }
166
167 }