// News extension for App Inventor by Marco Perrone package News; import com.google.appinventor.components.runtime.*; import android.app.Activity; import android.content.Intent; import com.google.appinventor.components.annotations.DesignerComponent; import com.google.appinventor.components.annotations.DesignerProperty; import com.google.appinventor.components.annotations.PropertyCategory; import com.google.appinventor.components.annotations.SimpleFunction; import com.google.appinventor.components.annotations.SimpleEvent; import com.google.appinventor.components.annotations.SimpleObject; import com.google.appinventor.components.annotations.SimpleProperty; import com.google.appinventor.components.annotations.UsesPermissions; import com.google.appinventor.components.annotations.UsesActivities; import com.google.appinventor.components.annotations.UsesLibraries; import com.google.appinventor.components.annotations.UsesActivityMetadata; import com.google.appinventor.components.annotations.androidmanifest.*; import com.google.appinventor.components.common.ComponentCategory; import com.google.appinventor.components.common.PropertyTypeConstants; import com.google.appinventor.components.common.YaVersion; import com.google.appinventor.components.runtime.util.GingerbreadUtil; import com.google.appinventor.components.runtime.util.SdkLevel; import com.google.appinventor.components.runtime.util.AsynchUtil; import com.google.appinventor.components.runtime.util.YailList; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.CookieHandler; import java.util.Scanner; import java.util.Iterator; import java.util.Map; import java.util.List; import java.util.ArrayList; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.StringWriter; import java.io.PrintWriter; import java.io.IOException; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.DataOutputStream; import java.io.BufferedReader; import java.io.OutputStream; @SimpleObject(external=true) @UsesPermissions(permissionNames = "android.permission.INTERNET") @DesignerComponent(version = YaVersion.WEB_COMPONENT_VERSION, description = "

Non-visible component to search news from all over the world.", category = ComponentCategory.EXTENSION, nonVisible = true, iconName = "images/nearfield.png") public class News extends AndroidNonvisibleComponent implements Component { private final Activity activity; private final CookieHandler cookieHandler; private String twoHyphens = "--"; private String boundary = "*****"+Long.toString(System.currentTimeMillis())+"*****"; private String LINE = "\r\n"; private URL url; private HttpURLConnection httpConn = null; private OutputStream outputStream; private PrintWriter writer; private String charset = "utf-8"; @SimpleEvent(description = "Got News") public void GotNews(int responseCode, String response, YailList source, YailList author, YailList title, YailList description, YailList urlArticle, YailList urlImage, String message) { EventDispatcher.dispatchEvent(this, "GotNews", responseCode, response, source, author, title, description, urlArticle, urlImage, message); } @SimpleFunction(description = "Get News") public void GetNews(final String query, final String from, final String to, final String language, final String sortby, final String pagesize, final String apikey) { AsynchUtil.runAsynchronously(new Runnable() { @Override public void run() { String URLStr = "https://newsapi.org/v2/everything?"; if (pagesize.length() != 0) { URLStr = URLStr + "pagesize=" + pagesize; } else { URLStr = URLStr + "pagesize=10"; } if (query.length() != 0) { URLStr = URLStr + "&q=" + query; } if (from.length() != 0) { URLStr = URLStr + "&from=" + from; } if (to.length() != 0) { URLStr = URLStr + "&to=" + to; } if (language.length() != 0) { URLStr = URLStr + "&language=" + language; } else { URLStr = URLStr + "&language=en"; } if (sortby.length() != 0) { URLStr = URLStr + "&sortby=" + sortby; } else { URLStr = URLStr + "&sortby=relevance"; } GetNews_Exec(URLStr, apikey); } }); } @SimpleFunction(description = "Get Top Headlines") public void GetTopHeadlines(final String query, final String category, final String country, final String pagesize, final String apikey) { AsynchUtil.runAsynchronously(new Runnable() { @Override public void run() { String URLStr = "https://newsapi.org/v2/top-headlines?"; if (pagesize.length() != 0) { URLStr = URLStr + "pagesize=" + pagesize; } else { URLStr = URLStr + "pagesize=10"; } if (query.length() != 0) { URLStr = URLStr + "&q=" + query; } if (category.length() != 0) { URLStr = URLStr + "&category=" + category; } if (country.length() != 0) { URLStr = URLStr + "&country=" + country; } GetNews_Exec(URLStr, apikey); } }); } public News(ComponentContainer container) { super(container.$form()); activity = container.$context(); cookieHandler = (SdkLevel.getLevel() >= SdkLevel.LEVEL_GINGERBREAD) ? GingerbreadUtil.newCookieManager() : null; } void GetNews_Exec(String URLStr, String APIKEY) { try { InputStream inputStream = null; URL url = new URL(URLStr); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setRequestMethod("GET"); httpConn.setRequestProperty("Connection", "Keep-Alive"); httpConn.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0"); httpConn.setRequestProperty("Authorization", APIKEY); final int status = httpConn.getResponseCode(); List source = new ArrayList(); List author = new ArrayList(); List title = new ArrayList(); List description = new ArrayList(); List urlArticle = new ArrayList(); List urlImage = new ArrayList(); String Msg = ""; if (status == HttpURLConnection.HTTP_OK) { inputStream = httpConn.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); String inputLine; final StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } final String responseStr = response.toString(); String ImportantValues = ""; String name = ""; String authorStr = ""; String titleStr = ""; String descStr = ""; String urlArtStr = ""; String urlImgStr = ""; if (responseStr.indexOf("name") != -1) { ImportantValues = responseStr; while (ImportantValues.indexOf("name") != -1) { ImportantValues = ImportantValues.substring(ImportantValues.indexOf("name")+7); name = ImportantValues.substring(0,ImportantValues.indexOf("\"")); name = name.replace("\\",""); source.add(name); authorStr = ImportantValues.substring(ImportantValues.indexOf("author")+9); authorStr = authorStr.substring(0,authorStr.indexOf("\"")); authorStr = authorStr.replace("\\",""); if (authorStr.compareTo("ull,") == 0) { authorStr = "unavailable"; } author.add(authorStr); titleStr = ImportantValues.substring(ImportantValues.indexOf("title")+8); titleStr = titleStr.substring(0,titleStr.indexOf("\",")); titleStr = titleStr.replace("\\",""); title.add(titleStr); descStr = ImportantValues.substring(ImportantValues.indexOf("description")+14); descStr = descStr.substring(0,descStr.indexOf("\",")); descStr = descStr.replace("\\",""); if (descStr.compareTo("ull,") == 0) { descStr = "unavailable"; } description.add(descStr); urlArtStr = ImportantValues.substring(ImportantValues.indexOf("url")+6); urlArtStr = urlArtStr.substring(0,urlArtStr.indexOf("\",")); urlArticle.add(urlArtStr); urlImgStr = ImportantValues.substring(ImportantValues.indexOf("urlToImage")+13); urlImgStr = urlImgStr.substring(0,urlImgStr.indexOf("\",")); urlImage.add(urlImgStr); } } else { if (responseStr.indexOf("message") != -1) { Msg = responseStr.substring(responseStr.indexOf("message")+10); Msg = Msg.substring(0,Msg.indexOf("\"")); } else { Msg = "No results found"; } } httpConn.disconnect(); final List sourceFin = source; final List authorFin = author; final List titleFin = title; final List descriptionFin = description; final List urlArticleFin = urlArticle; final List urlImageFin = urlImage; final String Message = Msg; // Dispatch the event. activity.runOnUiThread(new Runnable() { @Override public void run() { GotNews(status, responseStr , YailList.makeList(sourceFin), YailList.makeList(authorFin), YailList.makeList(titleFin), YailList.makeList(descriptionFin), YailList.makeList(urlArticleFin), YailList.makeList(urlImageFin), Message); } }); } else { InputStream inputStreamErr = httpConn.getErrorStream(); BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); String inputLine; final StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } final String responseStr = response.toString(); httpConn.disconnect(); // Dispatch the event. activity.runOnUiThread(new Runnable() { @Override public void run() { GotNews(status, responseStr , null, null, null, null, null, null, ""); } }); } } catch (Exception e) { e.printStackTrace(); StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); appendLog(errors.toString()); } } public void appendLog(String text) { File logFile = new File("sdcard/NewsLog.txt"); if (!logFile.exists()) { try { logFile.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } try { //BufferedWriter for performance, true to set append to file flag BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); buf.append(text); buf.newLine(); buf.flush(); buf.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }