Open source file übersetzen Phython -> Java

forreason

Mitglied
Hallo Community,
Ich habe hier ein Open Source Projekt basierend auf Python. Leider blicke ich bei Python nur äußerst spärlich durch. Dennoch könnte ich den Code sehr gut in einem Projekt von mir gebrauchen.
Konkret geht es darum, sich auf eine Mobile Api zu verbinden und daten (über cookies) auszulesen.
Da ich noch anfänger bin bräuchte ich den code, um mich daran zu orientieren und erstmal richtig zu verstehen was ich da genau mache.

hier der denke ich relevanteste teil
Code:
class EDAPI:
    '''
    A class that handles the Frontier ED API.
    '''

    _agent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 8_1 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) Mobile/12B411'  # NOQA
    _baseurl = 'https://companion.orerve.net/'
    _basename = 'edapi'
    _cookiefile = _basename + '.cookies'
    _envfile = _basename + '.vars'

    def __init__(
        self,
        basename='edapi',
        debug=False,
        cookiefile=None,
        json_file=None
    ):
        '''
        Initialize
        '''

        # Build common file names from basename.
        self._basename = basename
        if cookiefile:
            self._cookiefile = cookiefile
        else:
            self._cookiefile = self._basename + '.cookies'

        self._envfile = self._basename + '.vars'

        self.debug = debug

        # If json_file was given, just load that instead.
        if json_file:
            with open(json_file) as file:
                self.profile = json.load(file)
                return

        # if self.debug:
        #     import http.client
        #     http.client.HTTPConnection.debuglevel = 3

        # Setup the HTTP session.
        self.opener = requests.Session()

        self.opener.headers = {
            'User-Agent': self._agent
        }

        # Read/create the cookie jar.
        if os.path.exists(self._cookiefile):
            try:
                with open(self._cookiefile, 'rb') as h:
                    self.opener.cookies = cookiejar_from_dict(pickle.load(h))
            except:
                print('Unable to read cookie file.')

        else:
            with open(self._cookiefile, 'wb') as h:
                pickle.dump(dict_from_cookiejar(self.opener.cookies), h)

        # Grab the commander profile
        response = self._getURI('profile')
        try:
            self.profile = response.json()
        except:
            sys.exit('Unable to parse JSON response for /profile!\
                     Try with --debug and report this.')

    def _getBasicURI(self, uri, values=None):
        '''
        Perform a GET/POST to a URI
        '''

        # POST if data is present, otherwise GET.
        if values is None:
            if self.debug:
                print('GET on: ', self._baseurl+uri)
                print(dict_from_cookiejar(self.opener.cookies))
            response = self.opener.get(self._baseurl+uri)
        else:
            if self.debug:
                print('POST on: ', self._baseurl+uri)
                print(dict_from_cookiejar(self.opener.cookies))
            response = self.opener.post(self._baseurl+uri, data=values)

        if self.debug:
            print('Final URL:', response.url)
            print(dict_from_cookiejar(self.opener.cookies))

        # Save the cookies.
        with open(self._cookiefile, 'wb') as h:
            pickle.dump(dict_from_cookiejar(self.opener.cookies), h)

        # Return the response object.
        return response

    def _getURI(self, uri, values=None):
        '''
        Perform a GET/POST and try to login if needed.
        '''

        # Try the URI. If our credentials are no good, try to
        # login then ask again.
        response = self._getBasicURI(uri, values=values)

        if str(response.url).endswith('user/login'):
            self._doLogin()
            response = self._getBasicURI(uri, values=values)

        if str(response.url).endswith('user/login'):
            sys.exit(textwrap.fill(textwrap.dedent("""\
                Something went terribly wrong. The login credentials
                appear correct, but we are being denied access. Sometimes the
                API is slow to update, so if you are authenticating for the
                first time, wait a minute or so and try again. If this
                persists try using --debug and report this.
                """)))

        return response

    def _doLogin(self):
        '''
        Go though the login process
        '''
        # First hit the login page to get our auth cookies set.
        response = self._getBasicURI('')

        # Our current cookies look okay? No need to login.
        if str(response.url).endswith('/'):
            return

        # Perform the login POST.
        print(textwrap.fill(textwrap.dedent("""\
              You do not appear to have any valid login cookies set.
              We will attempt to log you in with your Frontier
              account, and cache your auth cookies for future use.
              THIS WILL NOT STORE YOUR USER NAME AND PASSWORD.
              """)))

        print("\nYour auth cookies will be stored here:")

        print("\n"+self._cookiefile+"\n")

        print(textwrap.fill(textwrap.dedent("""\
            It is advisable that you keep this file secret. It may
            be possible to hijack your account with the information
            it contains.
            """)))

        print(
            "\nIf you are not comfortable with this, "
            "DO NOT USE THIS TOOL."
        )
        print()

        values = {}
        values['email'] = input("User Name (email):")
        values['password'] = getpass.getpass()
        response = self._getBasicURI('user/login', values=values)

        # If we end up being redirected back to login,
        # the login failed.
        if str(response.url).endswith('user/login'):
            sys.exit('Login failed.')

        # Check to see if we need to do the auth token dance.
        if str(response.url).endswith('user/confirm'):
            print()
            print("A verification code should have been sent to your "
                  "email address.")
            print("Please provide that code (case sensitive!)")
            values = {}
            values['code'] = input("Code:")
            response = self._getBasicURI('user/confirm', values=values)
Der komplette Code (falls relevant) befindet sich im Anhang
Vielen dank schon mal 🙂
Anhang anzeigen edapi.txt
(ist eine.py datei, aber man kann keine .py hochladen, daher.txt)
 
Zuletzt bearbeitet:
Hallo Community,
Ich habe hier ein Open Source Projekt basierend auf Python. Leider blicke ich bei Python nur äußerst spärlich durch. Dennoch könnte ich den Code sehr gut in einem Projekt von mir gebrauchen.
Konkret geht es darum, sich auf eine Mobile Api zu verbinden und daten (über cookies) auszulesen.
Da ich noch anfänger bin bräuchte ich den code, um mich daran zu orientieren und erstmal richtig zu verstehen was ich da genau mache.

Und was willst du jetzt von uns? 😉

Du bist zwar "Anfänger" ... brauchst aber Code um dich mit einer mobile API zu verbinden und Cookies zu verwenden.
Hört sich für mich nicht mehr ganz nach Anfänger an -> Und selbst wenn so schwer schaut dieser Phyton Code nicht aus ... ein paar Methoden, Konsolenausgaben, if-Bedingungen, .....

Was willst du bei deinem Projekt genau erreichen? Vielleicht gibt es schon eine passende Java Lösung und man muss nicht umständlich Phyton in Java umschreiben.
 
bin schon weiter gekommen 🙂

eine passende Java Lösung gibt es (noch) nicht.
Die Api ist ursprünglich für eine IOS APP, um jederzeit Ingamedaten anzuschauen wie Geld, Hafen, alle Items am hafen etc. (eigentlich eine recht unnütze APP).

Die Idee ist nun, die Daten automatisiert abzugreifen und in eine Datenbank der Community einzuspeisen.
Per "crowdfunding" können so große mengen an Handelsdaten aktuell gehalten werden, so, dass sich effektive Routenplaner realisieren lassen.

Was ich nun noch an code brauche ist folgendes:
Code:
values = {}
        values['email'] = input("User Name (email):")
        values['password'] = getpass.getpass()
        response = self._getBasicURI('user/login', values=values)

Code:
response = self.opener.post(self._baseurl+uri, data=values)

das ganze habe ich bereits so versucht umzusetzen:
Java:
con.setRequestMethod("POST");
        con.setRequestProperty("email", "***@***.com");
                con.setRequestProperty("password", "***");
 
        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.flush();
        wr.close();

allerdings bekomme ich den error 403 - forbidden

Code:
Sending 'POST' request to URL : https://companion.orerve.net/user/login
Response Code : 403
Exception in thread "main" java.io.IOException: Server returned HTTP response code: 403 for URL: https://companion.orerve.net/user/login
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1676)
    at sun.net.www.protocol.http.HttpURLConnection$6.run(HttpURLConnection.java:1674)
    at java.security.AccessController.doPrivileged(Native Method)
    at sun.net.www.protocol.http.HttpURLConnection.getChainedException(HttpURLConnection.java:1672)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1245)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at httptest.Httptest.sendPost(Httptest.java:110)
    at httptest.Httptest.main(Httptest.java:41)
Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: https://companion.orerve.net/user/login
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627)
    at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
    at httptest.Httptest.sendPost(Httptest.java:105)
    ... 1 more
Java Result: 1

vielen Dank für Hilfe
 
Zuletzt bearbeitet:
Eine API-Beschreibung gibt es nicht, die API ist eben eigentlich für die Offizielle App gedacht.

Allerdings bin ich wieder einen Schritt weiter. Der Fehler war, dass ich den "User-Agent" nicht angegeben habe.
 

Zurück
Oben