package failchat.twitch;

import failchat.core.ViewersCounter;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;

import java.net.URL;

public class TwitchViewersCounter implements ViewersCounter {
    private static final String VIEWERS_API_URL = "https://api.twitch.tv/kraken/streams/";
    private String channel;
    private int viewers = -1;

    public TwitchViewersCounter(String channel) {
        this.channel = channel;
    }

    @Override
    public int getViewersCount() {
        return viewers;
    }

    @Override
    public void updateViewersCount() {
        try {
            URL globalEmotesUrl = new URL(VIEWERS_API_URL + channel);
            String rawJS = IOUtils.toString(globalEmotesUrl.openConnection().getInputStream());
            JSONObject responseObj = new JSONObject(rawJS);
            viewers = responseObj.getJSONObject("stream").getInt("viewers");
        } catch (Exception e) {
            viewers = -1;
        }
    }
}

@@ -139,79 +139,298 @@
 ava.
-net.URL;%0A%0Apublic class TwitchViewersCounter implements ViewersCounter %7B
+io.InputStream;%0Aimport java.net.URL;%0Aimport java.net.URLConnection;%0Aimport java.util.logging.Level;%0Aimport java.util.logging.Logger;%0A%0Apublic class TwitchViewersCounter implements ViewersCounter %7B%0A%0A    private static final Logger LOG = Logger.getLogger(TwitchViewersCounter.class.getName());
 %0A   
@@ -517,16 +517,17 @@
 eams/%22;%0A
+%0A
     priv
@@ -829,28 +829,19 @@
     URL 
-globalEmotes
+api
 Url = ne
@@ -890,60 +890,250 @@
     
-String rawJS = IOUtils.toString(globalEmotesUrl.open
+URLConnection urlConnection = apiUrl.openConnection();%0A            //todo token shouldn't be hardcoded%0A            urlConnection.setRequestProperty(%22Client-ID%22, %22o1flir755whtdb29otu0wekaif6mj5%22);%0A            try (InputStream inputStream = url
 Conn
@@ -1138,18 +1138,16 @@
 nnection
-()
 .getInpu
@@ -1156,18 +1156,91 @@
 tream())
-;%0A
+ %7B%0A                String rawResponse = IOUtils.toString(inputStream);%0A    
         
@@ -1254,27 +1254,30 @@
 NObject 
-r
+parsedR
 esponse
-Obj
  = new J
@@ -1293,13 +1293,23 @@
 (raw
-JS);%0A
+Response);%0A    
     
@@ -1330,19 +1330,22 @@
 s = 
-r
+parsedR
 esponse
-Obj
 .get
@@ -1380,24 +1380,38 @@
 %22viewers%22);%0A
+            %7D%0A
         %7D ca
@@ -1426,24 +1426,137 @@
 eption e) %7B%0A
+            LOG.log(Level.WARNING, e, () -%3E %22Failed to get twitch viewers count for channel '%22 + channel + %22'%22);%0A
             

Fix twitch viewers counter