You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

153 lines
6.4 KiB

11 years ago
package org.telegram.updatesreceivers;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
11 years ago
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
11 years ago
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
11 years ago
import org.apache.http.message.BasicNameValuePair;
11 years ago
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.telegram.api.Update;
11 years ago
import org.telegram.database.DatabaseManager;
11 years ago
import org.telegram.methods.Constants;
import org.telegram.methods.GetUpdates;
11 years ago
import org.telegram.services.BotLogger;
11 years ago
import org.telegram.updateshandlers.UpdatesCallback;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.util.ArrayList;
import java.util.List;
11 years ago
import java.util.concurrent.ConcurrentLinkedDeque;
11 years ago
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Thread to request updates with active wait
* @date 20 of June of 2015
*/
public class UpdatesThread {
11 years ago
private static volatile BotLogger log = BotLogger.getLogger(UpdatesThread.class.getName());
11 years ago
private final UpdatesCallback callback;
private final ReaderThread readerThread;
11 years ago
private final HandlerThread handlerThread;
11 years ago
private int lastReceivedUpdate;
private String token;
11 years ago
private final ConcurrentLinkedDeque<Update> receivedUpdates = new ConcurrentLinkedDeque<>();
11 years ago
public UpdatesThread(String token, UpdatesCallback callback) {
this.token = token;
this.callback = callback;
11 years ago
this.lastReceivedUpdate = DatabaseManager.getInstance().getLastUpdate(this.token);
11 years ago
this.readerThread = new ReaderThread();
this.readerThread.start();
this.handlerThread = new HandlerThread();
this.handlerThread.start();
11 years ago
}
private class ReaderThread extends Thread {
@Override
public void run() {
11 years ago
setPriority(Thread.MIN_PRIORITY);
11 years ago
while(true) {
GetUpdates request = new GetUpdates();
11 years ago
request.setLimit(100);
request.setOffset(lastReceivedUpdate + 1);
11 years ago
CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
String url = Constants.BASEURL + token + "/" + GetUpdates.PATH;
11 years ago
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nameValuePairs = new ArrayList<>();
11 years ago
nameValuePairs.add(new BasicNameValuePair(GetUpdates.OFFSET_FIELD, request.getOffset()+""));
11 years ago
nameValuePairs.add(new BasicNameValuePair(GetUpdates.LIMIT_FIELD, request.getLimit()+""));
if (request.getTimeout() != null) {
nameValuePairs.add(new BasicNameValuePair(GetUpdates.TIMEOUT_FIELD, request.getTimeout()+""));
}
11 years ago
try {
11 years ago
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
httpPost.addHeader("Content-type", "application/x-www-form-urlencoded");
httpPost.addHeader("charset", "UTF-8");
HttpResponse response;
log.debug(httpPost.toString());
response = httpclient.execute(httpPost);
11 years ago
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseContent = EntityUtils.toString(buf, "UTF-8");
try {
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean("ok")) {
throw new InvalidObjectException(jsonObject.toString());
}
JSONArray jsonArray = jsonObject.getJSONArray("result");
11 years ago
log.debug(jsonArray.toString());
11 years ago
if (jsonArray.length() != 0) {
for (int i = 0; i < jsonArray.length(); i++) {
Update update = new Update(jsonArray.getJSONObject(i));
if (update.getUpdateId() > lastReceivedUpdate) {
lastReceivedUpdate = update.getUpdateId();
11 years ago
receivedUpdates.addFirst(update);
11 years ago
}
}
11 years ago
synchronized (receivedUpdates) {
receivedUpdates.notifyAll();
}
11 years ago
} else {
try {
synchronized (this) {
this.wait(500);
}
} catch (InterruptedException e) {
log.error(e);
11 years ago
continue;
}
}
} catch (JSONException e) {
log.warning(e);
11 years ago
}
} catch (IOException e) {
log.warning(e);
11 years ago
}
}
}
}
11 years ago
private class HandlerThread extends Thread {
@Override
public void run() {
11 years ago
setPriority(Thread.MIN_PRIORITY);
11 years ago
while(true) {
11 years ago
try {
11 years ago
Update update = receivedUpdates.pollLast();
11 years ago
if (update == null) {
synchronized (receivedUpdates) {
try {
receivedUpdates.wait();
} catch (InterruptedException e) {
log.error(e);
continue;
}
11 years ago
update = receivedUpdates.pollLast();
11 years ago
if (update == null) {
continue;
}
11 years ago
}
}
11 years ago
DatabaseManager.getInstance().putLastUpdate(token, update.getUpdateId());
callback.onUpdateReceived(update);
} catch (Exception e) {
log.error(e);
11 years ago
}
}
}
}
11 years ago
}