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
.PhotoTakenBroadcastReceiver
;
12 import eu
.alefzero
.webdav
.OnDatatransferProgressListener
;
13 import com
.owncloud
.android
.utils
.OwnCloudClientUtils
;
15 import android
.accounts
.Account
;
16 import android
.app
.Notification
;
17 import android
.app
.NotificationManager
;
18 import android
.app
.PendingIntent
;
19 import android
.app
.Service
;
20 import android
.content
.Intent
;
21 import android
.os
.Handler
;
22 import android
.os
.HandlerThread
;
23 import android
.os
.IBinder
;
24 import android
.os
.Looper
;
25 import android
.os
.Message
;
26 import android
.os
.Process
;
27 import android
.util
.Log
;
28 import android
.webkit
.MimeTypeMap
;
29 import android
.widget
.RemoteViews
;
30 import com
.owncloud
.android
.R
;
31 import eu
.alefzero
.webdav
.WebdavClient
;
33 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
35 public static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
36 public static final String EXTRA_PARENT_DIR_ID
= "PARENT_DIR_ID";
37 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
38 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
39 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
41 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
42 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
43 public static final String KEY_ACCOUNT
= "ACCOUNT";
44 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
45 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
46 public static final String KEY_MIME_TYPE
= "MIME_TYPE";
47 public static final String KEY_INSTANT_UPLOAD
= "INSTANT_UPLOAD";
49 public static final int UPLOAD_SINGLE_FILE
= 0;
50 public static final int UPLOAD_MULTIPLE_FILES
= 1;
52 private static final String TAG
= "FileUploader";
54 private NotificationManager mNotificationManager
;
55 private Looper mServiceLooper
;
56 private ServiceHandler mServiceHandler
;
57 private Account mAccount
;
58 private String
[] mLocalPaths
, mRemotePaths
, mMimeTypes
;
59 private int mUploadType
;
60 private Notification mNotification
;
61 private long mTotalDataToSend
, mSendData
;
62 private int mCurrentIndexUpload
, mPreviousPercent
;
63 private int mSuccessCounter
;
64 private boolean mIsInstant
;
67 * Static map with the files being download and the path to the temporal file were are download
69 private static Map
<String
, String
> mUploadsInProgress
= Collections
.synchronizedMap(new HashMap
<String
, String
>());
72 * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
74 public static boolean isUploading(Account account
, String remotePath
) {
75 return (mUploadsInProgress
.get(buildRemoteName(account
.name
, remotePath
)) != null
);
79 * Builds a key for mUplaodsInProgress from the accountName and remotePath
81 private static String
buildRemoteName(String accountName
, String remotePath
) {
82 return accountName
+ remotePath
;
89 public IBinder
onBind(Intent arg0
) {
93 private final class ServiceHandler
extends Handler
{
94 public ServiceHandler(Looper looper
) {
99 public void handleMessage(Message msg
) {
106 public void onCreate() {
108 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
109 HandlerThread thread
= new HandlerThread("FileUploaderThread",
110 Process
.THREAD_PRIORITY_BACKGROUND
);
112 mServiceLooper
= thread
.getLooper();
113 mServiceHandler
= new ServiceHandler(mServiceLooper
);
117 public int onStartCommand(Intent intent
, int flags
, int startId
) {
118 if (!intent
.hasExtra(KEY_ACCOUNT
) && !intent
.hasExtra(KEY_UPLOAD_TYPE
)) {
119 Log
.e(TAG
, "Not enough information provided in intent");
120 return Service
.START_NOT_STICKY
;
122 mAccount
= intent
.getParcelableExtra(KEY_ACCOUNT
);
123 mUploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
124 if (mUploadType
== -1) {
125 Log
.e(TAG
, "Incorrect upload type provided");
126 return Service
.START_NOT_STICKY
;
128 if (mUploadType
== UPLOAD_SINGLE_FILE
) {
129 mLocalPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
130 mRemotePaths
= new String
[] { intent
131 .getStringExtra(KEY_REMOTE_FILE
) };
132 mMimeTypes
= new String
[] { intent
.getStringExtra(KEY_MIME_TYPE
) };
134 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
135 mLocalPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
136 mRemotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
137 mMimeTypes
= intent
.getStringArrayExtra(KEY_MIME_TYPE
);
140 if (mLocalPaths
.length
!= mRemotePaths
.length
) {
141 Log
.e(TAG
, "Different number of remote paths and local paths!");
142 return Service
.START_NOT_STICKY
;
145 mIsInstant
= intent
.getBooleanExtra(KEY_INSTANT_UPLOAD
, false
);
147 Message msg
= mServiceHandler
.obtainMessage();
149 mServiceHandler
.sendMessage(msg
);
151 return Service
.START_NOT_STICKY
;
156 * Core upload method: sends the file(s) to upload
158 public void uploadFile() {
159 FileDataStorageManager storageManager
= new FileDataStorageManager(mAccount
, getContentResolver());
161 mTotalDataToSend
= mSendData
= mPreviousPercent
= 0;
163 /// prepare client object to send the request to the ownCloud server
164 WebdavClient wc
= OwnCloudClientUtils
.createOwnCloudClient(mAccount
, getApplicationContext());
165 wc
.setDataTransferProgressListener(this);
167 /// create status notification to show the upload progress
168 mNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
), System
.currentTimeMillis());
169 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
170 RemoteViews oldContentView
= mNotification
.contentView
;
171 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
172 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
173 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
174 // dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
175 // 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
176 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
177 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
179 /// create remote folder for instant uploads if necessary
181 OCFile instantUploadDir
= storageManager
.getFileByPath(PhotoTakenBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
182 if (instantUploadDir
== null
) {
183 wc
.createDirectory(PhotoTakenBroadcastReceiver
.INSTANT_UPLOAD_DIR
); // fail could just mean that it already exists, but local database is not synchronized; the upload will be started anyway
184 OCFile newDir
= new OCFile(PhotoTakenBroadcastReceiver
.INSTANT_UPLOAD_DIR
);
185 newDir
.setMimetype("DIR");
186 newDir
.setParentId(storageManager
.getFileByPath(OCFile
.PATH_SEPARATOR
).getFileId());
187 storageManager
.saveFile(newDir
);
191 /// perform the upload
192 File
[] localFiles
= new File
[mLocalPaths
.length
];
193 for (int i
= 0; i
< mLocalPaths
.length
; ++i
) {
194 localFiles
[i
] = new File(mLocalPaths
[i
]);
195 mTotalDataToSend
+= localFiles
[i
].length();
197 Log
.d(TAG
, "Will upload " + mTotalDataToSend
+ " bytes, with " + mLocalPaths
.length
+ " files");
199 for (int i
= 0; i
< mLocalPaths
.length
; ++i
) {
200 String mimeType
= (mMimeTypes
!= null
) ? mMimeTypes
[i
] : null
;
201 if (mimeType
== null
) {
203 mimeType
= MimeTypeMap
.getSingleton()
204 .getMimeTypeFromExtension(
205 mLocalPaths
[i
].substring(mLocalPaths
[i
]
206 .lastIndexOf('.') + 1));
207 } catch (IndexOutOfBoundsException e
) {
208 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + mLocalPaths
[i
]);
211 if (mimeType
== null
)
212 mimeType
= "application/octet-stream";
213 mCurrentIndexUpload
= i
;
214 long parentDirId
= -1;
215 boolean uploadResult
= false
;
216 String availablePath
= getAvailableRemotePath(wc
, mRemotePaths
[i
]);
218 File f
= new File(mRemotePaths
[i
]);
219 parentDirId
= storageManager
.getFileByPath(f
.getParent().endsWith("/")?f
.getParent():f
.getParent()+"/").getFileId();
220 if(availablePath
!= null
) {
221 mRemotePaths
[i
] = availablePath
;
222 mUploadsInProgress
.put(buildRemoteName(mAccount
.name
, mRemotePaths
[i
]), mLocalPaths
[i
]);
223 if (wc
.putFile(mLocalPaths
[i
], mRemotePaths
[i
], mimeType
)) {
224 OCFile new_file
= new OCFile(mRemotePaths
[i
]);
225 new_file
.setMimetype(mimeType
);
226 new_file
.setFileLength(localFiles
[i
].length());
227 new_file
.setModificationTimestamp(System
.currentTimeMillis());
228 new_file
.setLastSyncDate(0);
229 new_file
.setStoragePath(mLocalPaths
[i
]);
230 new_file
.setParentId(parentDirId
);
231 storageManager
.saveFile(new_file
);
237 mUploadsInProgress
.remove(buildRemoteName(mAccount
.name
, mRemotePaths
[i
]));
239 /// notify upload (or fail) of EACH file to activities interested
240 Intent end
= new Intent(UPLOAD_FINISH_MESSAGE
);
241 end
.putExtra(EXTRA_PARENT_DIR_ID
, parentDirId
);
242 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
);
243 end
.putExtra(EXTRA_REMOTE_PATH
, mRemotePaths
[i
]);
244 end
.putExtra(EXTRA_FILE_PATH
, mLocalPaths
[i
]);
245 end
.putExtra(ACCOUNT_NAME
, mAccount
.name
);
251 /// notify final result
252 if (mSuccessCounter
== mLocalPaths
.length
) { // success
253 //Notification finalNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_succeeded_ticker), System.currentTimeMillis());
254 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove the ongoing flag
255 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
256 mNotification
.contentView
= oldContentView
;
257 // TODO put something smart in the contentIntent below
258 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
259 if (mLocalPaths
.length
== 1) {
260 mNotification
.setLatestEventInfo( getApplicationContext(),
261 getString(R
.string
.uploader_upload_succeeded_ticker
),
262 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), localFiles
[0].getName()),
263 mNotification
.contentIntent
);
265 mNotification
.setLatestEventInfo( getApplicationContext(),
266 getString(R
.string
.uploader_upload_succeeded_ticker
),
267 String
.format(getString(R
.string
.uploader_upload_succeeded_content_multiple
), mSuccessCounter
),
268 mNotification
.contentIntent
);
270 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
273 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
274 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
275 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
276 // TODO put something smart in the contentIntent below
277 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
278 if (mLocalPaths
.length
== 1) {
279 finalNotification
.setLatestEventInfo( getApplicationContext(),
280 getString(R
.string
.uploader_upload_failed_ticker
),
281 String
.format(getString(R
.string
.uploader_upload_failed_content_single
), localFiles
[0].getName()),
282 finalNotification
.contentIntent
);
284 finalNotification
.setLatestEventInfo( getApplicationContext(),
285 getString(R
.string
.uploader_upload_failed_ticker
),
286 String
.format(getString(R
.string
.uploader_upload_failed_content_multiple
), mSuccessCounter
, mLocalPaths
.length
),
287 finalNotification
.contentIntent
);
289 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
295 * Checks if remotePath does not exist in the server and returns it, or adds a suffix to it in order to avoid the server
296 * file is overwritten.
301 private String
getAvailableRemotePath(WebdavClient wc
, String remotePath
) {
302 Boolean check
= wc
.existsFile(remotePath
);
303 if (check
== null
) { // null means fail
309 int pos
= remotePath
.lastIndexOf(".");
311 String extension
= "";
313 extension
= remotePath
.substring(pos
+1);
314 remotePath
= remotePath
.substring(0, pos
);
317 while (check
!= null
&& check
) {
318 suffix
= " (" + count
+ ")";
320 check
= wc
.existsFile(remotePath
+ suffix
+ "." + extension
);
322 check
= wc
.existsFile(remotePath
+ suffix
);
327 } else if (pos
>=0) {
328 return remotePath
+ suffix
+ "." + extension
;
330 return remotePath
+ suffix
;
336 * Callback method to update the progress bar in the status notification.
339 public void transferProgress(long progressRate
) {
340 mSendData
+= progressRate
;
341 int percent
= (int)(100*((double)mSendData
)/((double)mTotalDataToSend
));
342 if (percent
!= mPreviousPercent
) {
343 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, new File(mLocalPaths
[mCurrentIndexUpload
]).getName());
344 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
345 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
346 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
348 mPreviousPercent
= percent
;