package com.prime31;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import com.prime31.TwitterDialog;
import com.tapjoy.TapjoyConstants;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Iterator;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.TwitterApi;
import org.scribe.model.OAuthConstants;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;

/* loaded from: /storage/emulated/0/Documents/jadec/sources/com.UBI.A90.WW/dex-files/2.dex */
public class TwitterPlugin {
    private static TwitterPlugin _instance = null;
    private static final String apiUploadUrlPrefix = "http://upload.twitter.com";
    private static final String apiUrlPrefix = "https://api.twitter.com";
    public static final String callbackUrlPrefix = "twitterplugin";
    private Token _accessToken;
    public Activity _activity;
    private Token _requestToken;
    private OAuthService _service;
    private TwitterSession _session;
    private Field _unityPlayerActivityField;
    private Class<?> _unityPlayerClass;
    private Method _unitySendMessageMethod;

    public static TwitterPlugin instance() {
        if (_instance == null) {
            _instance = new TwitterPlugin();
        }
        return _instance;
    }

    public TwitterPlugin() {
        try {
            this._unityPlayerClass = Class.forName("com.unity3d.player.UnityPlayer");
            this._unityPlayerActivityField = this._unityPlayerClass.getField("currentActivity");
            this._unitySendMessageMethod = this._unityPlayerClass.getMethod("UnitySendMessage", String.class, String.class, String.class);
        } catch (ClassNotFoundException e) {
            Log.i("Prime31", "could not find UnityPlayer class: " + e.getMessage());
        } catch (NoSuchFieldException e2) {
            Log.i("Prime31", "could not find currentActivity field: " + e2.getMessage());
        } catch (Exception e3) {
            Log.i("Prime31", "unkown exception occurred locating UnityPlayer.currentActivity: " + e3.getMessage());
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public Activity getActivity() {
        if (this._unityPlayerActivityField != null) {
            try {
                return (Activity) this._unityPlayerActivityField.get(this._unityPlayerClass);
            } catch (Exception e) {
                Log.i("Prime31", "error getting currentActivity: " + e.getMessage());
            }
        }
        return this._activity;
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void UnitySendMessage(String go, String m, String p) {
        if (this._unitySendMessageMethod != null) {
            try {
                this._unitySendMessageMethod.invoke(null, go, m, p);
                return;
            } catch (IllegalAccessException e) {
                Log.i("Prime31", "could not find UnitySendMessage method: " + e.getMessage());
                return;
            } catch (IllegalArgumentException e2) {
                Log.i("Prime31", "could not find UnitySendMessage method: " + e2.getMessage());
                return;
            } catch (InvocationTargetException e3) {
                Log.i("Prime31", "could not find UnitySendMessage method: " + e3.getMessage());
                return;
            }
        }
        Log.i("Prime31", "UnitySendMessage: " + go + ", " + m + ", " + p);
    }

    private void showLoginDialog(final String url) {
        if (isLoggedIn()) {
            UnitySendMessage("TwitterAndroidManager", "loginDidSucceed", this._session.getUsername());
        } else {
            getActivity().runOnUiThread(new Runnable() { // from class: com.prime31.TwitterPlugin.1
                @Override // java.lang.Runnable
                public void run() {
                    TwitterDialog.DialogListener listener = new TwitterDialog.DialogListener() { // from class: com.prime31.TwitterPlugin.1.1
                        @Override // com.prime31.TwitterDialog.DialogListener
                        public void onComplete(String value) {
                            int i = 0;
                            Log.i("Prime31", "login complete. fetching oauth_verifier");
                            try {
                                boolean foundVerifier = false;
                                URL url2 = new URL(value.replace(TwitterPlugin.callbackUrlPrefix, "http"));
                                String query = url2.getQuery();
                                String verifier = null;
                                String[] array = query.split("&");
                                int length = array.length;
                                while (true) {
                                    if (i >= length) {
                                        break;
                                    }
                                    String parameter = array[i];
                                    String[] v = parameter.split("=");
                                    if (!URLDecoder.decode(v[0]).equals(OAuthConstants.VERIFIER)) {
                                        i++;
                                    } else {
                                        verifier = URLDecoder.decode(v[1]);
                                        foundVerifier = true;
                                        Log.i("Prime31", "found verifier");
                                        break;
                                    }
                                }
                                if (!foundVerifier) {
                                    TwitterPlugin.this.UnitySendMessage("TwitterAndroidManager", "loginDidFail", "cancelled");
                                } else {
                                    TwitterPlugin.this.continueLoginWithVerifier(verifier);
                                }
                            } catch (MalformedURLException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override // com.prime31.TwitterDialog.DialogListener
                        public void onError(String value) {
                            TwitterPlugin.this.UnitySendMessage("TwitterAndroidManager", "loginDidFail", value);
                        }
                    };
                    Log.i("Prime31", "prepping login dialog with url: " + url);
                    TwitterDialog dialog = new TwitterDialog(TwitterPlugin.this.getActivity(), url, listener);
                    dialog.setOnCancelListener(new DialogInterface.OnCancelListener() { // from class: com.prime31.TwitterPlugin.1.2
                        @Override // android.content.DialogInterface.OnCancelListener
                        public void onCancel(DialogInterface arg0) {
                            TwitterPlugin.this.UnitySendMessage("TwitterAndroidManager", "loginDidFail", "cancelled");
                        }
                    });
                    dialog.show();
                }
            });
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void continueLoginWithVerifier(final String oauthVerifier) {
        new Thread(new Runnable() { // from class: com.prime31.TwitterPlugin.2
            @Override // java.lang.Runnable
            public void run() {
                Log.i("Prime31", "continuing login with verifier");
                try {
                    Verifier verifier = new Verifier(oauthVerifier);
                    Log.i("Prime31", "Fetching access token");
                    TwitterPlugin.this._accessToken = TwitterPlugin.this._service.getAccessToken(TwitterPlugin.this._requestToken, verifier);
                    Log.i("Prime31", "Got access token. preparing request to verify_credentials");
                    OAuthRequest request = new OAuthRequest(Verb.GET, "https://api.twitter.com/1/account/verify_credentials.json");
                    TwitterPlugin.this._service.signRequest(TwitterPlugin.this._accessToken, request);
                    Response response = request.send();
                    try {
                        Log.i("Prime31", "credentials verified. getting body");
                        JSONObject post = new JSONObject(response.getBody());
                        String username = post.getString(TapjoyConstants.TJC_EVENT_IAP_NAME);
                        TwitterPlugin.this._session.storeAccessToken(TwitterPlugin.this._accessToken, username);
                        TwitterPlugin.this.UnitySendMessage("TwitterAndroidManager", "loginDidSucceed", username);
                    } catch (JSONException e) {
                        TwitterPlugin.this.UnitySendMessage("TwitterAndroidManager", "loginDidFail", e.getMessage());
                    }
                } catch (IllegalArgumentException iae) {
                    TwitterPlugin.this.UnitySendMessage("TwitterAndroidManager", "loginDidFail", iae.getMessage());
                } catch (Exception e2) {
                    TwitterPlugin.this.UnitySendMessage("TwitterAndroidManager", "loginDidFail", e2.getMessage());
                }
            }
        }).start();
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void performRequestInternal(String type, String path, Bundle params) {
        Verb verb;
        try {
            if (type.compareToIgnoreCase("get") == 0) {
                verb = Verb.GET;
            } else {
                verb = Verb.POST;
            }
            if (!path.startsWith("/")) {
                path = "/" + path;
            }
            OAuthRequest request = new OAuthRequest(verb, apiUrlPrefix + path);
            if (params != null) {
                Set<String> allKeys = params.keySet();
                for (String key : allKeys) {
                    request.addQuerystringParameter(key, params.getString(key));
                }
            }
            this._service.signRequest(this._accessToken, request);
            Response response = request.send();
            UnitySendMessage("TwitterAndroidManager", "requestSucceeded", response.getBody());
        } catch (Exception e) {
            String message = e.getMessage();
            if (message == null) {
                message = "Error performing request";
            }
            UnitySendMessage("TwitterAndroidManager", "requestFailed", message);
        }
    }

    /* JADX INFO: Access modifiers changed from: private */
    public void performMultipartRequestInternal(String path, Bundle params, byte[] image) {
        try {
            OAuthRequest request = new OAuthRequest(Verb.POST, apiUploadUrlPrefix + path);
            request.addHeader("Content-Type", "multipart/form-data; boundary=---------------------------14737809831466499882746641449");
            request.addHeader("Connection", "Keep-Alive");
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            os.write(("-----------------------------14737809831466499882746641449\r\n").getBytes());
            os.write("Content-Disposition: attachment; name=\"media[]\"; filename=\"screenshot.png\"\r\n".getBytes());
            os.write("Content-Type: application/octet-stream\r\n\r\n".getBytes());
            os.write(image);
            os.write("\r\n".getBytes());
            os.write(("-----------------------------14737809831466499882746641449\r\n").getBytes());
            os.write("Content-Disposition: form-data; name=\"status\"\r\n\r\n".getBytes());
            os.write(params.getString("status").getBytes());
            os.write("\r\n".getBytes());
            os.write(("-----------------------------14737809831466499882746641449--\r\n").getBytes());
            request.addPayload(os.toByteArray());
            this._service.signRequest(this._accessToken, request);
            Response response = request.send();
            UnitySendMessage("TwitterAndroidManager", "requestSucceeded", response.getBody());
        } catch (Exception e) {
            String message = e.getMessage();
            if (message == null) {
                message = "Error performing request";
            }
            UnitySendMessage("TwitterAndroidManager", "requestFailed", message);
        }
    }

    public void init(final String consumerKey, final String consumerSecret) {
        new Thread(new Runnable() { // from class: com.prime31.TwitterPlugin.3
            @Override // java.lang.Runnable
            public void run() {
                Log.i("Prime31", "initializing Twitter service");
                TwitterPlugin.this._session = new TwitterSession(TwitterPlugin.this.getActivity());
                TwitterPlugin.this._accessToken = TwitterPlugin.this._session.getAccessToken();
                TwitterPlugin.this._service = new ServiceBuilder().provider(TwitterApi.SSL.class).apiKey(consumerKey).apiSecret(consumerSecret).callback("twitterplugin://connect").build();
                try {
                    if (!TwitterPlugin.this.isLoggedIn()) {
                        TwitterPlugin.this._requestToken = TwitterPlugin.this._service.getRequestToken();
                    }
                } catch (Exception e) {
                    Log.i("Prime31", "error getting token: " + e.getMessage());
                }
                TwitterPlugin.this.UnitySendMessage("TwitterAndroidManager", "twitterInitialized", "");
                Log.i("Prime31", "initialized Twitter service. got requestToken");
            }
        }).start();
    }

    public boolean isLoggedIn() {
        return this._accessToken != null;
    }

    public void showLoginDialog() {
        if (this._service == null) {
            Log.i("Prime31", "service is null.  We can't do anything until init is called");
            return;
        }
        try {
            if (this._requestToken == null) {
                this._requestToken = this._service.getRequestToken();
            }
            Log.i("Prime31", "got reqeust token. showing login dialog");
            String authUrl = this._service.getAuthorizationUrl(this._requestToken);
            showLoginDialog(authUrl);
        } catch (Exception e) {
            UnitySendMessage("TwitterAndroidManager", "loginDidFail", e.getMessage());
            Log.i("Prime31", "error getting token: " + e.getMessage());
        }
    }

    public void logout() {
        this._session.resetAccessToken();
        this._service = null;
        this._accessToken = null;
        this._requestToken = null;
    }

    public void postUpdateWithImage(final String update, final byte[] image) {
        new Thread(new Runnable() { // from class: com.prime31.TwitterPlugin.4
            @Override // java.lang.Runnable
            public void run() {
                Bundle params = new Bundle();
                params.putString("status", update);
                TwitterPlugin.this.performMultipartRequestInternal("/1/statuses/update_with_media.json", params, image);
            }
        }).start();
    }

    public void performRequest(final String type, final String path, final String jsonString) {
        new Thread(new Runnable() { // from class: com.prime31.TwitterPlugin.5
            @Override // java.lang.Runnable
            public void run() {
                Bundle bundle = null;
                try {
                    if (jsonString != null && jsonString.length() > 0) {
                        Bundle bundle2 = new Bundle();
                        try {
                            JSONObject json = new JSONObject(jsonString);
                            Iterator<String> iter = json.keys();
                            while (iter.hasNext()) {
                                String key = iter.next();
                                bundle2.putString(key, json.getString(key));
                            }
                            bundle = bundle2;
                        } catch (JSONException e) {
                            e = e;
                            Log.i("Prime31", "error decoding request data: " + e.getMessage());
                            return;
                        }
                    }
                    TwitterPlugin.this.performRequestInternal(type, path, bundle);
                } catch (JSONException e2) {
                    e = e2;
                }
            }
        }).start();
    }
}
