Skip to content

Android Integration

This is a very simple helper to call the Stream Server. See the reference for examples (select the StreamServerClient.java example tab).

Note

The abstraction level is about on the same as the HttpRequest.java of the original TV-Server. The students still have to implement AsyncTask and all the other stuff. Also the package definition in the first line needs to be updated.

StreamServerClient.java

Download ยท View in GitLab

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
package com.example.myapplication;

import android.net.Uri;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StreamServerClient {
    private Uri baseUri;

    /**
     * Creates a new instance of StreamServerClient.
     * The instance is very lightweight so it is okay to create a new instance for each request.
     *
     * @param ipAddressWithPort The IP address with port e.g. "10.0.2.2:8080"
     */
    public StreamServerClient(String ipAddressWithPort) {
        baseUri = Uri.parse("http://" + ipAddressWithPort);
    }

    /**
     * Creates a new instance of StreamServerClient.
     * The instance is very lightweight so it is okay to create a new instance for each request.
     *
     * @param ipAddress The IP address e.g. "10.0.2.2"
     * @param port The port e.g. 8080
     */
    public StreamServerClient(String ipAddress, int port) {
        baseUri = Uri.parse("http://" + ipAddress + ":" + port);
    }

    private String doRequest(String path, @Nullable Map<String, String> params) throws IOException {
        Uri.Builder builder = baseUri.buildUpon().appendEncodedPath(path.substring(1));

        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.appendQueryParameter(entry.getKey(), entry.getValue());
            }
        }

        URL url = new URL(builder.build().toString());

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        try {
            conn.connect();
            int status = conn.getResponseCode();

            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
                sb.append("\n"); // add the stripped line back
            }
            br.close();

            String content = sb.toString();

            if (status != HttpURLConnection.HTTP_OK) { // status != 200
                throw new IOException(String.format("HTTP request %s failed with status %d and content: %s", conn, status, content));
            }

            return content;
        } finally {
            conn.disconnect();
        }
    }

    private List<JSONObject> jsonArrayToJsonObjectList(JSONArray array) throws JSONException {
        List<JSONObject> list = new ArrayList<>();

        for (int i = 0; i < array.length(); i++) {
            list.add(array.getJSONObject(i));
        }

        return list;
    }

    /**
     * Updates and returns the new state of the display.
     * Reference at <a href="https://stream-server.h-da.io/reference#display">https://stream-server.h-da.io/reference#display</a>
     *
     * @param large_channel Sets the channel name of the large screen.
     *                      This screen is the always visible main screen.
     *                      Set to "" to disable. Set to null to keep the old value.
     *
     * @param small_channel Sets the channel name of the small screen.
     *                      This screen is a small Picture-in-Picture like screen in the top right corner.
     *                      Set to "" to disable. Set to null to keep the old value.
     *
     * @param volume Sets the volume of the large screen.
     *               Set to 0 or 0.0 to mute.
     *               Values are in the range of 0.0 - 1.0.
     *               Note: The small screen is always muted.
     *               Set to null to keep the old value.
     *
     * @param small_scale Sets the scale (size) of the small screen.
     *                    The value is relative to the width of the large screen.
     *                    Reasonable values are in the range of 0.2 - 0.5.
     *                    It is best to just experiment with this setting.
     *                    Set to null to keep the old value.
     *
     * @param show_chat Sets whether the chat should be shown or not.
     *                  Set to null to keep the old value.
     */
    public JSONObject display(@Nullable String large_channel, @Nullable String small_channel, @Nullable Float volume, @Nullable Float small_scale, @Nullable Boolean show_chat) throws IOException, JSONException {
        Map<String, String> params = new HashMap<>();
        if (large_channel != null) {
            params.put("large_channel", large_channel);
        }

        if (small_channel != null) {
            params.put("small_channel", small_channel);
        }

        if (volume != null) {
            params.put("volume", volume.toString());
        }

        if (small_scale != null) {
            params.put("small_scale", small_scale.toString());
        }

        if (show_chat != null) {
            params.put("show_chat", show_chat.toString());
        }

        String content = doRequest("/display", params);
        return new JSONObject(content);
    }

    /**
     * Gets the most popular games on Twitch right now.
     * Reference at <a href="https://stream-server.h-da.io/reference#twitchgettopgames">https://stream-server.h-da.io/reference#twitchgamestop</a>
     */
    public List<JSONObject> twitchGetTopGames() throws IOException, JSONException {
        String content = doRequest("/twitch/getTopGames", null);

        return jsonArrayToJsonObjectList(new JSONArray(content));
    }

    /**
     * Searches games by query.
     * Reference at <a href="https://stream-server.h-da.io/reference#twitchsearchgames">https://stream-server.h-da.io/reference#twitchsearchgames</a>
     *
     * @param query What should be searched.
     */
    public List<JSONObject> twitchSearchGames(@NonNull String query) throws IOException, JSONException {
        Map<String, String> params = new HashMap<>();
        params.put("query", query);

        String content = doRequest("/twitch/searchGames", params);

        return jsonArrayToJsonObjectList(new JSONArray(content));
    }

    /**
     * Gets the most popular streams on Twitch right now. Optionally filter by channels, game and language.
     * Reference at <a href="https://stream-server.h-da.io/reference#twitchgettopstreams">https://stream-server.h-da.io/reference#twitchgettopstreams</a>
     *
     * @param channels Specify up to 100 channels separated by `,` that the search should be limited to.
     *                 See the examples in the reference why that would be useful.
     *
     * @param game Specify a game that the search should be limited to.
     *
     * @param language Specify a language that the search should be limited to.
     */
    public List<JSONObject> twitchGetTopStreams(@Nullable String[] channels, @Nullable String game, @Nullable String language) throws IOException, JSONException {
        Map<String, String> params = new HashMap<>();
        if (channels != null) {
            params.put("channels", TextUtils.join(",", channels));
        }

        if (game != null) {
            params.put("game", game);
        }

        if (language != null) {
            params.put("language", language);
        }

        String content = doRequest("/twitch/getTopStreams", params);

        return jsonArrayToJsonObjectList(new JSONArray(content));
    }

    /**
     * Gets the featured games on Twitch's homepage.
     * Reference at <a href="https://stream-server.h-da.io/reference#twitchgetfeaturedstreams">https://stream-server.h-da.io/reference#twitchgetfeaturedstreams</a>
     */
    public List<JSONObject> twitchGetFeaturedStreams() throws IOException, JSONException {
        String content = doRequest("/twitch/getFeaturedStreams", null);

        return jsonArrayToJsonObjectList(new JSONArray(content));
    }
}

Last update: June 20, 2020