1 package eu
.alefzero
.owncloud
.files
.services
;
4 import java
.util
.Collections
;
5 import java
.util
.HashMap
;
8 import android
.accounts
.Account
;
9 import android
.app
.Notification
;
10 import android
.app
.NotificationManager
;
11 import android
.app
.PendingIntent
;
12 import android
.app
.Service
;
13 import android
.content
.Intent
;
14 import android
.os
.Handler
;
15 import android
.os
.HandlerThread
;
16 import android
.os
.IBinder
;
17 import android
.os
.Looper
;
18 import android
.os
.Message
;
19 import android
.os
.Process
;
20 import android
.util
.Log
;
21 import android
.webkit
.MimeTypeMap
;
22 import android
.widget
.RemoteViews
;
23 import eu
.alefzero
.owncloud
.R
;
24 import eu
.alefzero
.owncloud
.datamodel
.FileDataStorageManager
;
25 import eu
.alefzero
.owncloud
.datamodel
.OCFile
;
26 import eu
.alefzero
.owncloud
.files
.interfaces
.OnDatatransferProgressListener
;
27 import eu
.alefzero
.webdav
.WebdavClient
;
29 public class FileUploader
extends Service
implements OnDatatransferProgressListener
{
31 public static final String UPLOAD_FINISH_MESSAGE
= "UPLOAD_FINISH";
32 public static final String EXTRA_PARENT_DIR_ID
= "PARENT_DIR_ID";
33 public static final String EXTRA_UPLOAD_RESULT
= "RESULT";
34 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
35 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
37 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
38 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
39 public static final String KEY_ACCOUNT
= "ACCOUNT";
40 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
41 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
43 public static final int UPLOAD_SINGLE_FILE
= 0;
44 public static final int UPLOAD_MULTIPLE_FILES
= 1;
46 private static final String TAG
= "FileUploader";
48 private NotificationManager mNotificationManager
;
49 private Looper mServiceLooper
;
50 private ServiceHandler mServiceHandler
;
51 private Account mAccount
;
52 private String
[] mLocalPaths
, mRemotePaths
;
53 private int mUploadType
;
54 private Notification mNotification
;
55 private long mTotalDataToSend
, mSendData
;
56 private int mCurrentIndexUpload
, mPreviousPercent
;
57 private int mSuccessCounter
;
60 * Static map with the files being download and the path to the temporal file were are download
62 private static Map
<String
, String
> mUploadsInProgress
= Collections
.synchronizedMap(new HashMap
<String
, String
>());
65 * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
67 public static boolean isUploading(Account account
, String remotePath
) {
68 return (mUploadsInProgress
.get(buildRemoteName(account
.name
, remotePath
)) != null
);
72 * Builds a key for mUplaodsInProgress from the accountName and remotePath
74 private static String
buildRemoteName(String accountName
, String remotePath
) {
75 return accountName
+ remotePath
;
82 public IBinder
onBind(Intent arg0
) {
86 private final class ServiceHandler
extends Handler
{
87 public ServiceHandler(Looper looper
) {
92 public void handleMessage(Message msg
) {
99 public void onCreate() {
101 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
102 HandlerThread thread
= new HandlerThread("FileUploaderThread",
103 Process
.THREAD_PRIORITY_BACKGROUND
);
105 mServiceLooper
= thread
.getLooper();
106 mServiceHandler
= new ServiceHandler(mServiceLooper
);
110 public int onStartCommand(Intent intent
, int flags
, int startId
) {
111 if (!intent
.hasExtra(KEY_ACCOUNT
) && !intent
.hasExtra(KEY_UPLOAD_TYPE
)) {
112 Log
.e(TAG
, "Not enough information provided in intent");
113 return Service
.START_NOT_STICKY
;
115 mAccount
= intent
.getParcelableExtra(KEY_ACCOUNT
);
116 mUploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
117 if (mUploadType
== -1) {
118 Log
.e(TAG
, "Incorrect upload type provided");
119 return Service
.START_NOT_STICKY
;
121 if (mUploadType
== UPLOAD_SINGLE_FILE
) {
122 mLocalPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
123 mRemotePaths
= new String
[] { intent
124 .getStringExtra(KEY_REMOTE_FILE
) };
125 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
126 mLocalPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
127 mRemotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
130 if (mLocalPaths
.length
!= mRemotePaths
.length
) {
131 Log
.e(TAG
, "Different number of remote paths and local paths!");
132 return Service
.START_NOT_STICKY
;
135 Message msg
= mServiceHandler
.obtainMessage();
137 mServiceHandler
.sendMessage(msg
);
139 return Service
.START_NOT_STICKY
;
144 * Core upload method: sends the file(s) to upload
146 public void uploadFile() {
147 FileDataStorageManager storageManager
= new FileDataStorageManager(mAccount
, getContentResolver());
149 mTotalDataToSend
= mSendData
= mPreviousPercent
= 0;
151 /// prepare client object to send the request to the ownCloud server
152 WebdavClient wc
= new WebdavClient(mAccount
, getApplicationContext());
153 wc
.allowSelfsignedCertificates();
154 wc
.setDataTransferProgressListener(this);
156 /// create status notification to show the upload progress
157 mNotification
= new Notification(eu
.alefzero
.owncloud
.R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
), System
.currentTimeMillis());
158 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
159 RemoteViews oldContentView
= mNotification
.contentView
;
160 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
161 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
162 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
163 // dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
164 // 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
165 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
166 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
169 /// perform the upload
170 File
[] localFiles
= new File
[mLocalPaths
.length
];
171 for (int i
= 0; i
< mLocalPaths
.length
; ++i
) {
172 localFiles
[i
] = new File(mLocalPaths
[i
]);
173 mTotalDataToSend
+= localFiles
[i
].length();
175 Log
.d(TAG
, "Will upload " + mTotalDataToSend
+ " bytes, with " + mLocalPaths
.length
+ " files");
177 for (int i
= 0; i
< mLocalPaths
.length
; ++i
) {
178 String mimeType
= null
;
180 mimeType
= MimeTypeMap
.getSingleton()
181 .getMimeTypeFromExtension(
182 mLocalPaths
[i
].substring(mLocalPaths
[i
]
183 .lastIndexOf('.') + 1));
184 } catch (IndexOutOfBoundsException e
) {
185 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + mLocalPaths
[i
]);
187 if (mimeType
== null
)
188 mimeType
= "application/octet-stream";
189 mCurrentIndexUpload
= i
;
190 long parentDirId
= -1;
191 boolean uploadResult
= false
;
192 String availablePath
= getAvailableRemotePath(wc
, mRemotePaths
[i
]);
194 File f
= new File(mRemotePaths
[i
]);
195 parentDirId
= storageManager
.getFileByPath(f
.getParent().endsWith("/")?f
.getParent():f
.getParent()+"/").getFileId();
196 if(availablePath
!= null
) {
197 mRemotePaths
[i
] = availablePath
;
198 mUploadsInProgress
.put(buildRemoteName(mAccount
.name
, mRemotePaths
[i
]), mLocalPaths
[i
]);
199 if (wc
.putFile(mLocalPaths
[i
], mRemotePaths
[i
], mimeType
)) {
200 OCFile new_file
= new OCFile(mRemotePaths
[i
]);
201 new_file
.setMimetype(mimeType
);
202 new_file
.setFileLength(localFiles
[i
].length());
203 new_file
.setModificationTimestamp(System
.currentTimeMillis());
204 new_file
.setLastSyncDate(0);
205 new_file
.setStoragePath(mLocalPaths
[i
]);
206 new_file
.setParentId(parentDirId
);
207 storageManager
.saveFile(new_file
);
213 mUploadsInProgress
.remove(buildRemoteName(mAccount
.name
, mRemotePaths
[i
]));
215 /// notify upload (or fail) of EACH file to activities interested
216 Intent end
= new Intent(UPLOAD_FINISH_MESSAGE
);
217 end
.putExtra(EXTRA_PARENT_DIR_ID
, parentDirId
);
218 end
.putExtra(EXTRA_UPLOAD_RESULT
, uploadResult
);
219 end
.putExtra(EXTRA_REMOTE_PATH
, mRemotePaths
[i
]);
220 end
.putExtra(EXTRA_FILE_PATH
, mLocalPaths
[i
]);
221 end
.putExtra(ACCOUNT_NAME
, mAccount
.name
);
227 /// notify final result
228 if (mSuccessCounter
== mLocalPaths
.length
) { // success
229 //Notification finalNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_succeeded_ticker), System.currentTimeMillis());
230 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove the ongoing flag
231 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
232 mNotification
.contentView
= oldContentView
;
233 // TODO put something smart in the contentIntent below
234 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
235 if (mLocalPaths
.length
== 1) {
236 mNotification
.setLatestEventInfo( getApplicationContext(),
237 getString(R
.string
.uploader_upload_succeeded_ticker
),
238 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), localFiles
[0].getName()),
239 mNotification
.contentIntent
);
241 mNotification
.setLatestEventInfo( getApplicationContext(),
242 getString(R
.string
.uploader_upload_succeeded_ticker
),
243 String
.format(getString(R
.string
.uploader_upload_succeeded_content_multiple
), mSuccessCounter
),
244 mNotification
.contentIntent
);
246 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
249 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
250 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
251 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
252 // TODO put something smart in the contentIntent below
253 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
254 if (mLocalPaths
.length
== 1) {
255 finalNotification
.setLatestEventInfo( getApplicationContext(),
256 getString(R
.string
.uploader_upload_failed_ticker
),
257 String
.format(getString(R
.string
.uploader_upload_failed_content_single
), localFiles
[0].getName()),
258 finalNotification
.contentIntent
);
260 finalNotification
.setLatestEventInfo( getApplicationContext(),
261 getString(R
.string
.uploader_upload_failed_ticker
),
262 String
.format(getString(R
.string
.uploader_upload_failed_content_multiple
), mSuccessCounter
, mLocalPaths
.length
),
263 finalNotification
.contentIntent
);
265 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
271 * Checks if remotePath does not exist in the server and returns it, or adds a suffix to it in order to avoid the server
272 * file is overwritten.
277 private String
getAvailableRemotePath(WebdavClient wc
, String remotePath
) {
278 Boolean check
= wc
.existsFile(remotePath
);
279 if (check
== null
) { // null means fail
285 int pos
= remotePath
.lastIndexOf(".");
287 String extension
= "";
289 extension
= remotePath
.substring(pos
+1);
290 remotePath
= remotePath
.substring(0, pos
);
293 while (check
!= null
&& check
) {
294 suffix
= " (" + count
+ ")";
296 check
= wc
.existsFile(remotePath
+ suffix
+ "." + extension
);
298 check
= wc
.existsFile(remotePath
+ suffix
);
303 } else if (pos
>=0) {
304 return remotePath
+ suffix
+ "." + extension
;
306 return remotePath
+ suffix
;
312 * Callback method to update the progress bar in the status notification.
315 public void transferProgress(long progressRate
) {
316 mSendData
+= progressRate
;
317 int percent
= (int)(100*((double)mSendData
)/((double)mTotalDataToSend
));
318 if (percent
!= mPreviousPercent
) {
319 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, new File(mLocalPaths
[mCurrentIndexUpload
]).getName());
320 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
321 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
322 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
324 mPreviousPercent
= percent
;