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";
34 public static final String KEY_LOCAL_FILE
= "LOCAL_FILE";
35 public static final String KEY_REMOTE_FILE
= "REMOTE_FILE";
36 public static final String KEY_ACCOUNT
= "ACCOUNT";
37 public static final String KEY_UPLOAD_TYPE
= "UPLOAD_TYPE";
38 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
40 public static final int UPLOAD_SINGLE_FILE
= 0;
41 public static final int UPLOAD_MULTIPLE_FILES
= 1;
43 private static final String TAG
= "FileUploader";
45 private NotificationManager mNotificationManager
;
46 private Looper mServiceLooper
;
47 private ServiceHandler mServiceHandler
;
48 private Account mAccount
;
49 private String
[] mLocalPaths
, mRemotePaths
;
50 private int mUploadType
;
51 private Notification mNotification
;
52 private long mTotalDataToSend
, mSendData
;
53 private int mCurrentIndexUpload
, mPreviousPercent
;
54 private int mSuccessCounter
;
57 * Static map with the files being download and the path to the temporal file were are download
59 private static Map
<String
, String
> mUploadsInProgress
= Collections
.synchronizedMap(new HashMap
<String
, String
>());
62 * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading
64 public static boolean isUploading(Account account
, String remotePath
) {
65 return (mUploadsInProgress
.get(buildRemoteName(account
.name
, remotePath
)) != null
);
69 * Builds a key for mUplaodsInProgress from the accountName and remotePath
71 private static String
buildRemoteName(String accountName
, String remotePath
) {
72 return accountName
+ remotePath
;
79 public IBinder
onBind(Intent arg0
) {
83 private final class ServiceHandler
extends Handler
{
84 public ServiceHandler(Looper looper
) {
89 public void handleMessage(Message msg
) {
96 public void onCreate() {
98 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
99 HandlerThread thread
= new HandlerThread("FileUploaderThread",
100 Process
.THREAD_PRIORITY_BACKGROUND
);
102 mServiceLooper
= thread
.getLooper();
103 mServiceHandler
= new ServiceHandler(mServiceLooper
);
107 public int onStartCommand(Intent intent
, int flags
, int startId
) {
108 if (!intent
.hasExtra(KEY_ACCOUNT
) && !intent
.hasExtra(KEY_UPLOAD_TYPE
)) {
109 Log
.e(TAG
, "Not enough information provided in intent");
110 return Service
.START_NOT_STICKY
;
112 mAccount
= intent
.getParcelableExtra(KEY_ACCOUNT
);
113 mUploadType
= intent
.getIntExtra(KEY_UPLOAD_TYPE
, -1);
114 if (mUploadType
== -1) {
115 Log
.e(TAG
, "Incorrect upload type provided");
116 return Service
.START_NOT_STICKY
;
118 if (mUploadType
== UPLOAD_SINGLE_FILE
) {
119 mLocalPaths
= new String
[] { intent
.getStringExtra(KEY_LOCAL_FILE
) };
120 mRemotePaths
= new String
[] { intent
121 .getStringExtra(KEY_REMOTE_FILE
) };
122 } else { // mUploadType == UPLOAD_MULTIPLE_FILES
123 mLocalPaths
= intent
.getStringArrayExtra(KEY_LOCAL_FILE
);
124 mRemotePaths
= intent
.getStringArrayExtra(KEY_REMOTE_FILE
);
127 if (mLocalPaths
.length
!= mRemotePaths
.length
) {
128 Log
.e(TAG
, "Different number of remote paths and local paths!");
129 return Service
.START_NOT_STICKY
;
132 Message msg
= mServiceHandler
.obtainMessage();
134 mServiceHandler
.sendMessage(msg
);
136 return Service
.START_NOT_STICKY
;
141 * Core upload method: sends the file(s) to upload
143 public void uploadFile() {
144 FileDataStorageManager storageManager
= new FileDataStorageManager(mAccount
, getContentResolver());
146 mTotalDataToSend
= mSendData
= mPreviousPercent
= 0;
148 /// prepare client object to send the request to the ownCloud server
149 WebdavClient wc
= new WebdavClient(mAccount
, getApplicationContext());
150 wc
.allowSelfsignedCertificates();
151 wc
.setDataTransferProgressListener(this);
153 /// create status notification to show the upload progress
154 mNotification
= new Notification(eu
.alefzero
.owncloud
.R
.drawable
.icon
, getString(R
.string
.uploader_upload_in_progress_ticker
), System
.currentTimeMillis());
155 mNotification
.flags
|= Notification
.FLAG_ONGOING_EVENT
;
156 RemoteViews oldContentView
= mNotification
.contentView
;
157 mNotification
.contentView
= new RemoteViews(getApplicationContext().getPackageName(), R
.layout
.progressbar_layout
);
158 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, 0, false
);
159 mNotification
.contentView
.setImageViewResource(R
.id
.status_icon
, R
.drawable
.icon
);
160 // dvelasco ; contentIntent MUST be assigned to avoid app crashes in versions previous to Android 4.x ;
161 // 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
162 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
163 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
166 /// perform the upload
167 File
[] localFiles
= new File
[mLocalPaths
.length
];
168 for (int i
= 0; i
< mLocalPaths
.length
; ++i
) {
169 localFiles
[i
] = new File(mLocalPaths
[i
]);
170 mTotalDataToSend
+= localFiles
[i
].length();
172 Log
.d(TAG
, "Will upload " + mTotalDataToSend
+ " bytes, with " + mLocalPaths
.length
+ " files");
174 for (int i
= 0; i
< mLocalPaths
.length
; ++i
) {
175 String mimeType
= null
;
177 mimeType
= MimeTypeMap
.getSingleton()
178 .getMimeTypeFromExtension(
179 mLocalPaths
[i
].substring(mLocalPaths
[i
]
180 .lastIndexOf('.') + 1));
181 } catch (IndexOutOfBoundsException e
) {
182 Log
.e(TAG
, "Trying to find out MIME type of a file without extension: " + mLocalPaths
[i
]);
184 if (mimeType
== null
)
185 mimeType
= "application/octet-stream";
186 mCurrentIndexUpload
= i
;
187 mRemotePaths
[i
] = getAvailableRemotePath(wc
, mRemotePaths
[i
]);
188 mUploadsInProgress
.put(buildRemoteName(mAccount
.name
, mRemotePaths
[i
]), mLocalPaths
[i
]);
189 long parentDirId
= -1;
190 if (mRemotePaths
[i
] != null
&& wc
.putFile(mLocalPaths
[i
], mRemotePaths
[i
], mimeType
)) {
192 OCFile new_file
= new OCFile(mRemotePaths
[i
]);
193 new_file
.setMimetype(mimeType
);
194 new_file
.setFileLength(localFiles
[i
].length());
195 new_file
.setModificationTimestamp(System
.currentTimeMillis());
196 new_file
.setLastSyncDate(0);
197 new_file
.setStoragePath(mLocalPaths
[i
]);
198 File f
= new File(mRemotePaths
[i
]);
199 parentDirId
= storageManager
.getFileByPath(f
.getParent().endsWith("/")?f
.getParent():f
.getParent()+"/").getFileId();
200 new_file
.setParentId(parentDirId
);
201 storageManager
.saveFile(new_file
);
203 mUploadsInProgress
.remove(buildRemoteName(mAccount
.name
, mRemotePaths
[i
]));
205 /// notify upload of EACH file to activities interested
206 Intent end
= new Intent(UPLOAD_FINISH_MESSAGE
);
207 end
.putExtra(EXTRA_PARENT_DIR_ID
, parentDirId
);
208 end
.putExtra(ACCOUNT_NAME
, mAccount
.name
);
212 /// notify final result
213 if (mSuccessCounter
== mLocalPaths
.length
) { // success
214 //Notification finalNotification = new Notification(R.drawable.icon, getString(R.string.uploader_upload_succeeded_ticker), System.currentTimeMillis());
215 mNotification
.flags ^
= Notification
.FLAG_ONGOING_EVENT
; // remove the ongoing flag
216 mNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
217 mNotification
.contentView
= oldContentView
;
218 // TODO put something smart in the contentIntent below
219 mNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
220 if (mLocalPaths
.length
== 1) {
221 mNotification
.setLatestEventInfo( getApplicationContext(),
222 getString(R
.string
.uploader_upload_succeeded_ticker
),
223 String
.format(getString(R
.string
.uploader_upload_succeeded_content_single
), localFiles
[0].getName()),
224 mNotification
.contentIntent
);
226 mNotification
.setLatestEventInfo( getApplicationContext(),
227 getString(R
.string
.uploader_upload_succeeded_ticker
),
228 String
.format(getString(R
.string
.uploader_upload_succeeded_content_multiple
), mSuccessCounter
),
229 mNotification
.contentIntent
);
231 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
234 mNotificationManager
.cancel(R
.string
.uploader_upload_in_progress_ticker
);
235 Notification finalNotification
= new Notification(R
.drawable
.icon
, getString(R
.string
.uploader_upload_failed_ticker
), System
.currentTimeMillis());
236 finalNotification
.flags
|= Notification
.FLAG_AUTO_CANCEL
;
237 // TODO put something smart in the contentIntent below
238 finalNotification
.contentIntent
= PendingIntent
.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent
.FLAG_UPDATE_CURRENT
);
239 if (mLocalPaths
.length
== 1) {
240 finalNotification
.setLatestEventInfo( getApplicationContext(),
241 getString(R
.string
.uploader_upload_failed_ticker
),
242 String
.format(getString(R
.string
.uploader_upload_failed_content_single
), localFiles
[0].getName()),
243 finalNotification
.contentIntent
);
245 finalNotification
.setLatestEventInfo( getApplicationContext(),
246 getString(R
.string
.uploader_upload_failed_ticker
),
247 String
.format(getString(R
.string
.uploader_upload_failed_content_multiple
), mSuccessCounter
, mLocalPaths
.length
),
248 finalNotification
.contentIntent
);
250 mNotificationManager
.notify(R
.string
.uploader_upload_failed_ticker
, finalNotification
);
256 * Checks if remotePath does not exist in the server and returns it, or adds a suffix to it in order to avoid the server
257 * file is overwritten.
262 private String
getAvailableRemotePath(WebdavClient wc
, String remotePath
) {
263 Boolean check
= wc
.existsFile(remotePath
);
264 if (check
== null
) { // null means fail
270 int pos
= remotePath
.lastIndexOf(".");
272 String extension
= "";
274 extension
= remotePath
.substring(pos
+1);
275 remotePath
= remotePath
.substring(0, pos
);
278 while (check
!= null
&& check
) {
279 suffix
= " (" + count
+ ")";
281 check
= wc
.existsFile(remotePath
+ suffix
+ "." + extension
);
283 check
= wc
.existsFile(remotePath
+ suffix
);
288 } else if (pos
>=0) {
289 return remotePath
+ suffix
+ "." + extension
;
291 return remotePath
+ suffix
;
297 * Callback method to update the progress bar in the status notification.
300 public void transferProgress(long progressRate
) {
301 mSendData
+= progressRate
;
302 int percent
= (int)(100*((double)mSendData
)/((double)mTotalDataToSend
));
303 if (percent
!= mPreviousPercent
) {
304 String text
= String
.format(getString(R
.string
.uploader_upload_in_progress_content
), percent
, new File(mLocalPaths
[mCurrentIndexUpload
]).getName());
305 mNotification
.contentView
.setProgressBar(R
.id
.status_progress
, 100, percent
, false
);
306 mNotification
.contentView
.setTextViewText(R
.id
.status_text
, text
);
307 mNotificationManager
.notify(R
.string
.uploader_upload_in_progress_ticker
, mNotification
);
309 mPreviousPercent
= percent
;