Search in sources :

Example 71 with ResponseListener

use of com.connectsdk.service.capability.listeners.ResponseListener in project butter-android by butterproject.

the class WebOSWebAppSession method handleMediaCommandResponse.

@SuppressWarnings("unchecked")
public void handleMediaCommandResponse(final JSONObject payload) {
    String requestID = payload.optString("requestId");
    if (requestID.length() == 0)
        return;
    final ServiceCommand<ResponseListener<Object>> command = (ServiceCommand<ResponseListener<Object>>) mActiveCommands.get(requestID);
    if (command == null)
        return;
    String mError = payload.optString("error");
    if (mError.length() != 0) {
        Util.postError(command.getResponseListener(), new ServiceCommandError(0, mError, null));
    } else {
        Util.postSuccess(command.getResponseListener(), payload);
    }
    mActiveCommands.remove(requestID);
}
Also used : JSONObject(org.json.JSONObject) ServiceCommandError(com.connectsdk.service.command.ServiceCommandError) ResponseListener(com.connectsdk.service.capability.listeners.ResponseListener) ServiceCommand(com.connectsdk.service.command.ServiceCommand)

Example 72 with ResponseListener

use of com.connectsdk.service.capability.listeners.ResponseListener in project butter-android by butterproject.

the class WebOSWebAppSession method getDuration.

@Override
public void getDuration(final DurationListener listener) {
    int requestIdNumber = getNextId();
    final String requestId = String.format(Locale.US, "req%d", requestIdNumber);
    JSONObject message = null;
    try {
        message = new JSONObject() {

            {
                put("contentType", namespaceKey + "mediaCommand");
                put("mediaCommand", new JSONObject() {

                    {
                        put("type", "getDuration");
                        put("requestId", requestId);
                    }
                });
            }
        };
    } catch (JSONException e) {
        Util.postError(listener, new ServiceCommandError(0, "JSON Parse error", null));
    }
    ServiceCommand<ResponseListener<Object>> command = new ServiceCommand<ResponseListener<Object>>(null, null, null, new ResponseListener<Object>() {

        @Override
        public void onSuccess(Object response) {
            try {
                long position = ((JSONObject) response).getLong("duration");
                Util.postSuccess(listener, position * 1000);
            } catch (JSONException e) {
                Util.postError(listener, new ServiceCommandError(0, "JSON Parse error", null));
            }
        }

        @Override
        public void onError(ServiceCommandError error) {
            Util.postError(listener, error);
        }
    });
    mActiveCommands.put(requestId, command);
    sendMessage(message, new ResponseListener<Object>() {

        @Override
        public void onSuccess(Object response) {
        }

        @Override
        public void onError(ServiceCommandError error) {
            Util.postError(listener, error);
        }
    });
}
Also used : JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) ServiceCommandError(com.connectsdk.service.command.ServiceCommandError) JSONObject(org.json.JSONObject) ResponseListener(com.connectsdk.service.capability.listeners.ResponseListener) ServiceCommand(com.connectsdk.service.command.ServiceCommand)

Example 73 with ResponseListener

use of com.connectsdk.service.capability.listeners.ResponseListener in project butter-android by butterproject.

the class WebOSWebAppSession method getPlayState.

@Override
public void getPlayState(final PlayStateListener listener) {
    int requestIdNumber = getNextId();
    final String requestId = String.format(Locale.US, "req%d", requestIdNumber);
    JSONObject message = null;
    try {
        message = new JSONObject() {

            {
                put("contentType", namespaceKey + "mediaCommand");
                put("mediaCommand", new JSONObject() {

                    {
                        put("type", "getPlayState");
                        put("requestId", requestId);
                    }
                });
            }
        };
    } catch (JSONException e) {
        Util.postError(listener, new ServiceCommandError(0, "JSON Parse error", null));
    }
    ServiceCommand<ResponseListener<Object>> command = new ServiceCommand<ResponseListener<Object>>(null, null, null, new ResponseListener<Object>() {

        @Override
        public void onSuccess(Object response) {
            try {
                String playStateString = ((JSONObject) response).getString("playState");
                PlayStateStatus playState = parsePlayState(playStateString);
                Util.postSuccess(listener, playState);
            } catch (JSONException e) {
                this.onError(new ServiceCommandError(0, "JSON Parse error", null));
            }
        }

        @Override
        public void onError(ServiceCommandError error) {
            Util.postError(listener, error);
        }
    });
    mActiveCommands.put(requestId, command);
    sendMessage(message, new ResponseListener<Object>() {

        @Override
        public void onSuccess(Object response) {
        }

        @Override
        public void onError(ServiceCommandError error) {
            Util.postError(listener, error);
        }
    });
}
Also used : JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) ServiceCommandError(com.connectsdk.service.command.ServiceCommandError) JSONObject(org.json.JSONObject) ResponseListener(com.connectsdk.service.capability.listeners.ResponseListener) ServiceCommand(com.connectsdk.service.command.ServiceCommand)

Example 74 with ResponseListener

use of com.connectsdk.service.capability.listeners.ResponseListener in project butter-android by butterproject.

the class DLNAHttpServer method handleEntry.

private void handleEntry(JSONObject entry) throws JSONException {
    if (entry.has("TransportState")) {
        String transportState = entry.getString("TransportState");
        PlayStateStatus status = PlayStateStatus.convertTransportStateToPlayStateStatus(transportState);
        for (URLServiceSubscription<?> sub : subscriptions) {
            if (sub.getTarget().equalsIgnoreCase("playState")) {
                for (int j = 0; j < sub.getListeners().size(); j++) {
                    @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners().get(j);
                    Util.postSuccess(listener, status);
                }
            }
        }
    }
    if ((entry.has("Volume") && !entry.has("channel")) || (entry.has("Volume") && entry.getString("channel").equals("Master"))) {
        int intVolume = entry.getInt("Volume");
        float volume = (float) intVolume / 100;
        for (URLServiceSubscription<?> sub : subscriptions) {
            if (sub.getTarget().equalsIgnoreCase("volume")) {
                for (int j = 0; j < sub.getListeners().size(); j++) {
                    @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners().get(j);
                    Util.postSuccess(listener, volume);
                }
            }
        }
    }
    if ((entry.has("Mute") && !entry.has("channel")) || (entry.has("Mute") && entry.getString("channel").equals("Master"))) {
        String muteStatus = entry.getString("Mute");
        boolean mute;
        try {
            mute = (Integer.parseInt(muteStatus) == 1);
        } catch (NumberFormatException e) {
            mute = Boolean.parseBoolean(muteStatus);
        }
        for (URLServiceSubscription<?> sub : subscriptions) {
            if (sub.getTarget().equalsIgnoreCase("mute")) {
                for (int j = 0; j < sub.getListeners().size(); j++) {
                    @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners().get(j);
                    Util.postSuccess(listener, mute);
                }
            }
        }
    }
    if (entry.has("CurrentTrackMetaData")) {
        String trackMetaData = entry.getString("CurrentTrackMetaData");
        MediaInfo info = DLNAMediaInfoParser.getMediaInfo(trackMetaData);
        for (URLServiceSubscription<?> sub : subscriptions) {
            if (sub.getTarget().equalsIgnoreCase("info")) {
                for (int j = 0; j < sub.getListeners().size(); j++) {
                    @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners().get(j);
                    Util.postSuccess(listener, info);
                }
            }
        }
    }
}
Also used : MediaInfo(com.connectsdk.core.MediaInfo) PlayStateStatus(com.connectsdk.service.capability.MediaControl.PlayStateStatus) JSONObject(org.json.JSONObject) ResponseListener(com.connectsdk.service.capability.listeners.ResponseListener)

Example 75 with ResponseListener

use of com.connectsdk.service.capability.listeners.ResponseListener in project butter-android by butterproject.

the class NetcastHttpServer method start.

public void start() {
    // TODO: this method is too complex and should be refactored
    if (running)
        return;
    running = true;
    try {
        welcomeSocket = new ServerSocket(this.port);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    while (running) {
        if (welcomeSocket == null || welcomeSocket.isClosed()) {
            stop();
            break;
        }
        Socket connectionSocket = null;
        BufferedReader inFromClient = null;
        DataOutputStream outToClient = null;
        try {
            connectionSocket = welcomeSocket.accept();
        } catch (IOException ex) {
            ex.printStackTrace();
            // this socket may have been closed, so we'll stop
            stop();
            return;
        }
        String str = null;
        int c;
        StringBuilder sb = new StringBuilder();
        try {
            inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
            while ((str = inFromClient.readLine()) != null) {
                if (str.equals("")) {
                    break;
                }
            }
            while ((c = inFromClient.read()) != -1) {
                sb.append((char) c);
                String temp = sb.toString();
                if (temp.endsWith("</envelope>"))
                    break;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        String body = sb.toString();
        Log.d(Util.T, "got message body: " + body);
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = dateFormat.format(calendar.getTime());
        String androidOSVersion = android.os.Build.VERSION.RELEASE;
        PrintWriter out = null;
        try {
            outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            out = new PrintWriter(outToClient);
            out.println("HTTP/1.1 200 OK");
            out.println("Server: Android/" + androidOSVersion + " UDAP/2.0 ConnectSDK/1.2.1");
            out.println("Cache-Control: no-store, no-cache, must-revalidate");
            out.println("Date: " + date);
            out.println("Connection: Close");
            out.println("Content-Length: 0");
            out.println();
            out.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                inFromClient.close();
                out.close();
                outToClient.close();
                connectionSocket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        InputStream stream = null;
        try {
            stream = new ByteArrayInputStream(body.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }
        NetcastPOSTRequestParser handler = new NetcastPOSTRequestParser();
        SAXParser saxParser;
        try {
            saxParser = saxParserFactory.newSAXParser();
            saxParser.parse(stream, handler);
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        if (body.contains("ChannelChanged")) {
            ChannelInfo channel = NetcastChannelParser.parseRawChannelData(handler.getJSONObject());
            Log.d(Util.T, "Channel Changed: " + channel.getNumber());
            for (URLServiceSubscription<?> sub : subscriptions) {
                if (sub.getTarget().equalsIgnoreCase("ChannelChanged")) {
                    for (int i = 0; i < sub.getListeners().size(); i++) {
                        @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners().get(i);
                        Util.postSuccess(listener, channel);
                    }
                }
            }
        } else if (body.contains("KeyboardVisible")) {
            boolean focused = false;
            TextInputStatusInfo keyboard = new TextInputStatusInfo();
            keyboard.setRawData(handler.getJSONObject());
            try {
                JSONObject currentWidget = (JSONObject) handler.getJSONObject().get("currentWidget");
                focused = (Boolean) currentWidget.get("focus");
                keyboard.setFocused(focused);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.d(Util.T, "KeyboardFocused?: " + focused);
            for (URLServiceSubscription<?> sub : subscriptions) {
                if (sub.getTarget().equalsIgnoreCase("KeyboardVisible")) {
                    for (int i = 0; i < sub.getListeners().size(); i++) {
                        @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners().get(i);
                        Util.postSuccess(listener, keyboard);
                    }
                }
            }
        } else if (body.contains("TextEdited")) {
            System.out.println("TextEdited");
            String newValue = "";
            try {
                newValue = handler.getJSONObject().getString("value");
            } catch (JSONException ex) {
                ex.printStackTrace();
            }
            Util.postSuccess(textChangedListener, newValue);
        } else if (body.contains("3DMode")) {
            try {
                String enabled = (String) handler.getJSONObject().get("value");
                boolean bEnabled;
                bEnabled = enabled.equalsIgnoreCase("true");
                for (URLServiceSubscription<?> sub : subscriptions) {
                    if (sub.getTarget().equalsIgnoreCase("3DMode")) {
                        for (int i = 0; i < sub.getListeners().size(); i++) {
                            @SuppressWarnings("unchecked") ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners().get(i);
                            Util.postSuccess(listener, bEnabled);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}
Also used : DataOutputStream(java.io.DataOutputStream) ChannelInfo(com.connectsdk.core.ChannelInfo) SAXException(org.xml.sax.SAXException) URLServiceSubscription(com.connectsdk.service.command.URLServiceSubscription) SAXParser(javax.xml.parsers.SAXParser) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TextInputStatusInfo(com.connectsdk.core.TextInputStatusInfo) PrintWriter(java.io.PrintWriter) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Calendar(java.util.Calendar) UnsupportedEncodingException(java.io.UnsupportedEncodingException) JSONException(org.json.JSONException) ServerSocket(java.net.ServerSocket) IOException(java.io.IOException) ResponseListener(com.connectsdk.service.capability.listeners.ResponseListener) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) BufferedReader(java.io.BufferedReader) JSONObject(org.json.JSONObject) SimpleDateFormat(java.text.SimpleDateFormat) Socket(java.net.Socket) ServerSocket(java.net.ServerSocket) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Aggregations

ResponseListener (com.connectsdk.service.capability.listeners.ResponseListener)76 JSONObject (org.json.JSONObject)75 ServiceCommandError (com.connectsdk.service.command.ServiceCommandError)65 ServiceCommand (com.connectsdk.service.command.ServiceCommand)64 JSONException (org.json.JSONException)54 URLServiceSubscription (com.connectsdk.service.command.URLServiceSubscription)14 SuppressLint (android.annotation.SuppressLint)10 LaunchSession (com.connectsdk.service.sessions.LaunchSession)9 IOException (java.io.IOException)9 JSONArray (org.json.JSONArray)7 AppInfo (com.connectsdk.core.AppInfo)6 ChannelInfo (com.connectsdk.core.ChannelInfo)6 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 NameNotFoundException (android.content.pm.PackageManager.NameNotFoundException)3 HttpConnection (com.connectsdk.etc.helper.HttpConnection)3 InputStream (java.io.InputStream)3 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)3