1 package com
.owncloud
.android
.files
.services
;
4 import java
.util
.Collections
;
5 import java
.util
.HashMap
;
8 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
9 import com
.owncloud
.android
.datamodel
.OCFile
;
10 import com
.owncloud
.android
.files
.interfaces
.OnDatatransferProgressListener
;
12 import android
.accounts
.Account
;
13 import android
.app
.Notification
;
14 import android
.app
.NotificationManager
;
15 import android
.app
.PendingIntent
;
16 import android
.app
.Service
;
17 import android
.content
.Intent
;
18 import android
.os
.Handler
;
19 import android
.os
.HandlerThread
;
20 import android
.os
.IBinder
;
21 import android
.os
.Looper
;
22 import android
.os
.Message
;
23 import android
.os
.Process
;
24 import android
.util
.Log
;
25 import android
.webkit
.MimeTypeMap
;
26 import android
.widget
.RemoteViews
;
27 import com
.owncloud
.android
.R
;
28 import eu
.alefzero
.webdav
.WebdavClient
;
30 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
32 public static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
33 public static final String EXTRA_PARENT_DIR_ID
= "PARENT_DIR_ID";
34 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
35 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
36 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
38 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
39 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
40 public static final String KEY_ACCOUNT
= "ACCOUNT";
41 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
42 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
44 public static final int UPLOAD_SINGLE_FILE
= 0;
45 public static final int UPLOAD_MULTIPLE_FILES
= 1;
47 private static final String TAG
= "FileUploader";
49 private NotificationManager mNotificationManager
;
50 private Looper mServiceLooper
;
51 private ServiceHandler mServiceHandler
;
52 private Account mAccount
;
53 private String
[] mLocalPaths
, mRemotePaths
;
54 private int mUploadType
;
55 private Notification mNotification
;
56 private long mTotalDataToSend
, mSendData
;
57 private int mCurrentIndexUpload
, mPreviousPercent
;
58 private int mSuccessCounter
;
61 * Static map with the files being download and the path to the temporal file were are download
63 private static Map
<String
, String
> mUploadsInProgress
= Collections
.synchronizedMap(new HashMap
<String
, String
>());
66 * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
68 public static boolean isUploading(Account account
, String remotePath
) {
69 return (mUploadsInProgress
.get(buildRemoteName(account
.name
, remotePath
)) != null
);
73 * Builds a key for mUplaodsInProgress from the accountName and remotePath
75 private static String
buildRemoteName(String accountName
, String remotePath
) {
76 return accountName
+ remotePath
;
83 public IBinder
onBind(Intent arg0
) {
87 private final class ServiceHandler
extends Handler
{
88 public ServiceHandler(Looper looper
) {
93 public void handleMessage(Message msg
) {
100 public void onCreate() {
102 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
103 HandlerThread thread
= new HandlerThread("FileUploaderThread",
104 Process
.THREAD_PRIORITY_BACKGROUND
);
106 mServiceLooper
= thread
.getLooper();
107 mServiceHandler
= new ServiceHandler(mServiceLooper
);
111 public int onStartCommand(Intent intent
, int flags
, int startId
) {
112 if (!intent
.hasExtra(KEY_ACCOUNT
) && !intent
.hasExtra(KEY_UPLOAD_TYPE
)) {
113 Log
.e(TAG
, "Not enough information provided in intent");
114 return Service
.START_NOT_STICKY
;
116 mAccount
= intent
.getParcelableExtra(KEY_ACCOUNT
);
117 mUploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
118 if (mUploadType
== -1) {
119 Log
.e(TAG
, "Incorrect upload type provided");
120 return Service
.START_NOT_STICKY
;
122 if (mUploadType
== UPLOAD_SINGLE_FILE
) {
123 mLocalPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
124 mRemotePaths
= new String
[] { intent
125 .getStringExtra(KEY_REMOTE_FILE
) };
126 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
127 mLocalPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
128 mRemotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
131 if (mLocalPaths
.length
!= mRemotePaths
.length
) {
132 Log
.e(TAG
, "Different number of remote paths and local paths!");
133 return Service
.START_NOT_STICKY
;
136 Message msg
= mServiceHandler
.obtainMessage();
138 mServiceHandler
.sendMessage(msg
);
140 return Service
.START_NOT_STICKY
;
145 * Core upload method: sends the file(s) to upload
147 public void uploadFile() {
148 FileDataStorageManager storageManager
= new FileDataStorageManager(mAccount
, getContentResolver());
150 mTotalDataToSend
= mSendData
= mPreviousPercent
= 0;
152 /// prepare client object to send the request to the ownCloud server
153 WebdavClient wc
= new WebdavClient(mAccount
, getApplicationContext());
154 wc
.allowSelfsignedCertificates();
155 wc
.setDataTransferProgressListener(this);
157 /// create status notification to show the upload progress
158 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
), System
.currentTimeMillis());
159 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
160 RemoteViews oldContentView
= mNotification
.contentView
;
161 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
162 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
163 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
164 // dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
165 // BUT an empty Intent is not a very elegant solution; something smart should happen when a user 'clicks' on an upload in the notification bar
166 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
167 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
170 /// perform the upload
171 File
[] localFiles
= new File
[mLocalPaths
.length
];
172 for (int i
= 0; i
< mLocalPaths
.length
; ++i
) {
173 localFiles
[i
] = new File(mLocalPaths
[i
]);
174 mTotalDataToSend
+= localFiles
[i
].length();
176 Log
.d(TAG
, "Will upload " + mTotalDataToSend
+ " bytes, with " + mLocalPaths
.length
+ " files");
178 for (int i
= 0; i
< mLocalPaths
.length
; ++i
) {
179 String mimeType
= null
;
181 mimeType
= MimeTypeMap
.getSingleton()
182 .getMimeTypeFromExtension(
183 mLocalPaths
[i
].substring(mLocalPaths
[i
]
184 .lastIndexOf('.') + 1));
185 } catch (IndexOutOfBoundsException e
) {
186 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + mLocalPaths
[i
]);
188 if (mimeType
== null
)
189 mimeType
= "application/octet-stream";
190 mCurrentIndexUpload
= i
;
191 long parentDirId
= -1;
192 boolean uploadResult
= false
;
193 String availablePath
= getAvailableRemotePath(wc
, mRemotePaths
[i
]);
195 File f
= new File(mRemotePaths
[i
]);
196 parentDirId
= storageManager
.getFileByPath(f
.getParent().endsWith("/")?f
.getParent():f
.getParent()+"/").getFileId();
197 if(availablePath
!= null
) {
198 mRemotePaths
[i
] = availablePath
;
199 mUploadsInProgress
.put(buildRemoteName(mAccount
.name
, mRemotePaths
[i
]), mLocalPaths
[i
]);
200 if (wc
.putFile(mLocalPaths
[i
], mRemotePaths
[i
], mimeType
)) {
201 OCFile new_file
= new OCFile(mRemotePaths
[i
]);
202 new_file
.setMimetype(mimeType
);
203 new_file
.setFileLength(localFiles
[i
].length());
204 new_file
.setModificationTimestamp(System
.currentTimeMillis());
205 new_file
.setLastSyncDate(0);
206 new_file
.setStoragePath(mLocalPaths
[i
]);
207 new_file
.setParentId(parentDirId
);
208 storageManager
.saveFile(new_file
);
214 mUploadsInProgress
.remove(buildRemoteName(mAccount
.name
, mRemotePaths
[i
]));
216 /// notify upload (or fail) of EACH file to activities interested
217 Intent end
= new Intent(UPLOAD_FINISH_MESSAGE
);
218 end
.putExtra(EXTRA_PARENT_DIR_ID
, parentDirId
);
219 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
);
220 end
.putExtra(EXTRA_REMOTE_PATH
, mRemotePaths
[i
]);
221 end
.putExtra(EXTRA_FILE_PATH
, mLocalPaths
[i
]);
222 end
.putExtra(ACCOUNT_NAME
, mAccount
.name
);
228 /// notify final result
229 if (mSuccessCounter
== mLocalPaths
.length
) { // success
230 //Notification finalNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_succeeded_ticker), System.currentTimeMillis());
231 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove the ongoing flag
232 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
233 mNotification
.contentView
= oldContentView
;
234 // TODO put something smart in the contentIntent below
235 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
236 if (mLocalPaths
.length
== 1) {
237 mNotification
.setLatestEventInfo( getApplicationContext(),
238 getString(R
.string
.uploader_upload_succeeded_ticker
),
239 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), localFiles
[0].getName()),
240 mNotification
.contentIntent
);
242 mNotification
.setLatestEventInfo( getApplicationContext(),
243 getString(R
.string
.uploader_upload_succeeded_ticker
),
244 String
.format(getString(R
.string
.uploader_upload_succeeded_content_multiple
), mSuccessCounter
),
245 mNotification
.contentIntent
);
247 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
); // NOT AN ERROR; uploader_upload_in_progress_ticker is the target, not a new notification
250 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
251 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
252 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
253 // TODO put something smart in the contentIntent below
254 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
255 if (mLocalPaths
.length
== 1) {
256 finalNotification
.setLatestEventInfo( getApplicationContext(),
257 getString(R
.string
.uploader_upload_failed_ticker
),
258 String
.format(getString(R
.string
.uploader_upload_failed_content_single
), localFiles
[0].getName()),
259 finalNotification
.contentIntent
);
261 finalNotification
.setLatestEventInfo( getApplicationContext(),
262 getString(R
.string
.uploader_upload_failed_ticker
),
263 String
.format(getString(R
.string
.uploader_upload_failed_content_multiple
), mSuccessCounter
, mLocalPaths
.length
),
264 finalNotification
.contentIntent
);
266 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
272 * Checks if remotePath does not exist in the server and returns it, or adds a suffix to it in order to avoid the server
273 * file is overwritten.
278 private String
getAvailableRemotePath(WebdavClient wc
, String remotePath
) {
279 Boolean check
= wc
.existsFile(remotePath
);
280 if (check
== null
) { // null means fail
286 int pos
= remotePath
.lastIndexOf(".");
288 String extension
= "";
290 extension
= remotePath
.substring(pos
+1);
291 remotePath
= remotePath
.substring(0, pos
);
294 while (check
!= null
&& check
) {
295 suffix
= " (" + count
+ ")";
297 check
= wc
.existsFile(remotePath
+ suffix
+ "." + extension
);
299 check
= wc
.existsFile(remotePath
+ suffix
);
304 } else if (pos
>=0) {
305 return remotePath
+ suffix
+ "." + extension
;
307 return remotePath
+ suffix
;
313 * Callback method to update the progress bar in the status notification.
316 public void transferProgress(long progressRate
) {
317 mSendData
+= progressRate
;
318 int percent
= (int)(100*((double)mSendData
)/((double)mTotalDataToSend
));
319 if (percent
!= mPreviousPercent
) {
320 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, new File(mLocalPaths
[mCurrentIndexUpload
]).getName());
321 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
322 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
323 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
325 mPreviousPercent
= percent
;