Page 1 of 1

Sample - Using HTTPS to connect to server to transfer game data

Posted: Sun Jan 14, 2018 10:07 pm
by cookienomnom
Hi~
I don't know about you guys but I'm SUPER excited about the newest release!!
In the release note for 6.99.14, it says TLS has been added so now we can send game data to the server.
Does anyone have an example to show me how it's done?

Can't wait to try this out. Thanks a lot in advance!!

Re: Sample - Using HTTPS to connect to server to transfer game data

Posted: Sun Jan 14, 2018 10:18 pm
by Imperf3kt
Not sure if this is an actual answer, but here's an example by Xavimat from way before TLS was implemented.
viewtopic.php?f=11&t=41697

Re: Sample - Using HTTPS to connect to server to transfer game data

Posted: Sun Jan 14, 2018 11:49 pm
by PyTom
Right now, the most complete example is on my patreon, here:

https://www.patreon.com/posts/news-from-your-15636026

Re: Sample - Using HTTPS to connect to server to transfer game data

Posted: Mon Jan 15, 2018 2:08 am
by cookienomnom
Thanks PyTom for your response!
I looked at the link that you've posted and it seems like the post talks about fetching information from JSON file on the server to display the latest news on the client.
From the release note, I was under the impression that the new version allows data to be transferred FROM the client TO the server?

I'm hoping to save player progress on the server so that I can see how far the players have progressed.
Btw, thanks PyTom - your work and help is always appreciated!!!

Re: Sample - Using HTTPS to connect to server to transfer game data

Posted: Mon Jan 15, 2018 2:34 am
by PyTom
That's fair. The example I gave shows how to get requests going with Ren'Py. I'd suggest taking a look at the requests quickstart here:

http://docs.python-requests.org/en/mast ... uickstart/

to see how to use it to post to a server. As some advice, make sure you wrap everything in a try-except block, to make sure if it fails the game doesn't crash. (And any web request can fail.)

Re: Sample - Using HTTPS to connect to server to transfer game data

Posted: Mon Jan 15, 2018 10:58 am
by xavimat
(Probably I'm going to embarrass myself with the code below; I'm not professional and simply copy-paste code from tutorials, with lots of potential errors...)

I'm interested too in learning how the TLS works. This code here DOES NOT USE the new TLS thing (I need to study it, I don't have access to Renpytom's Patreon), but it uses old python2 libraries (urllib and urllib2) to connect to a HTTP (not HTTPS) url. I show this here only as a starting point, and ask for advice. What's wrong with my approach? How it should be done?

This is (simplified) the code I'm using in an app that informs a web server about the progress of the user. The user can also search for other users and follow them (set them as "friends"), and can see the progress other users have made (actually, there is a "champions chart", ordered by Xp points, not showed here). The user can also see what users are following him/her.
I'm showing here only some of the code:
1- connect.rpy, in Ren'Py, allows renpy to connect to the server.

Code: Select all

### CONNECT.rpy ###

default network = 1  ## this variable counts the times the urlopen has not been successful. 0==working
default webid = ''
default friends = []
default fans = []
default url = "http://mywebpage.com/mygame.php"
init python:
    from urllib import urlencode
    from urllib2 import urlopen
    from json import load as json_load

    def connect(action='inform'):

        global network, webid, friends, fans

        if webid == '':
            action = 'create'

        ## Preparation of data
        data_dict = {}
        data_dict['action'] = action

        if action == 'create':
            data_dict['username'] = username
        data_dict['pwh'] = pwh      ## password-hashed
        data_dict['webid'] = webid  ## user's id given by the server
        data_dict['version'] = config.version

        ## user's game progress:
        data_dict['xp'] =  xp
        data_dict['mascot'] = mascot

        data = urlencode(data_dict)

        try:
            response = urlopen(url, data=data, timeout=10)

        except:
            network += 1
            return False

        raw_result = json_load(response)

        response.close()

        friends = []
        fans = []

        if "CREATED" in raw_result:
            webid = str(raw_result["CREATED"])

        if "FRIENDS" in raw_result:
            for element in raw_result["FRIENDS"]:
                friends.append(element)

        if "FANS" in raw_result:
            for element in raw_result["FANS"]:
                fans.append(element)

        network = 0

        return True

Code: Select all

<?php
// Version: 04/01/2018

// RETRIEVE THE VARIABLES:
$webid = htmlspecialchars($_REQUEST['webid']);
$webid = intval($webid);
$username = htmlspecialchars($_REQUEST['username']);
$pwh = htmlspecialchars($_REQUEST['pwh']);
$xp = htmlspecialchars($_REQUEST['xp']);
$mascot = htmlspecialchars($_REQUEST['mascot']);
$version = htmlspecialchars($_REQUEST['version']);

// LINK WITH THE DATABASE:
$link = mysqli_connect("MySQL hostname", "MySQL username", "MySQL password", "MYSQL databasename");

// To show special characters:
$tildes = $link->query("SET NAMES 'utf8'");

// Arrays for the json output:
$a = array();
$friends = array();
$fans = array();

// Creates a new user:
if ($action == 'create') {
	// CREATE:
	$result = mysqli_query($link, "INSERT INTO mygame_users (username, pwh, xp, mascot, version)
		VALUES ('$username', '$pwh', '$xp', '$mascot', '$version')");
	$a["CREATED"] = mysqli_insert_id($link);

	$to = "some_email@mail.com";
	$subject = "MY GAME: New User";
	$message = "New User in my game: ".$username;
	mail($to, $subject, $message);

// Updates user info AND gets all friends and 100 fans:
} elseif ($action == 'inform') {
	// UPDATE INFO IN ROW...
	$result = mysqli_query($link, "UPDATE mygame_users
		SET xp = '$xp', mascot = '$mascot', version = '$version', updated=CURRENT_TIMESTAMP
		WHERE webid = '$webid' AND pwh = '$pwh'");
	// ...AND, IF SOME ROWS HAVE BEEN AFFECTED,...
	if (mysqli_affected_rows($link) > 0) {
		// ...GET THE FRIENDS...
		$result = mysqli_query($link, "SELECT webid, username, xp, mascot, id
			FROM mygame_users u
			INNER JOIN mygame_friends f ON u.webid = f.friendid
			WHERE f.userid = '$webid'");
			while ($row = mysqli_fetch_assoc($result)) {
				$friends[] = $row;
			}
			$a["FRIENDS"] = $friends;
		// ...AND GET THE FANS... (maximum 100)
		$result = mysqli_query($link, "SELECT webid, username, xp, mascot, id
			FROM mygame_users u
		  INNER JOIN mygame_friends f ON u.webid = f.userid
		  WHERE f.friendid = '$webid' ORDER BY last_done DESC, streak DESC LIMIT 100");
			while ($row = mysqli_fetch_assoc($result)) {
				$fans[] = $row;
			}
			$a["FANS"] = $fans;
	}
}

// HERE THERE IS MORE CODE TO SEARCH USERS, ADD THEM AS FRIENDS, 
//     DELETE FRIENDSHIP AND REPORT IN-GAME ERRORS.

// CLEANING UP:
mysqli_free_result($result);
mysqli_close($link);

// JSON OUTPUT:
echo json_encode($a, JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);


2- Then you need mygame.php, a PHP file in the server that dialogues with the database. With special attention to avoid SQL injection attacks.
- Takes the variables that the python code has passed (action, pwh, webid, version, xp, mascot).
- Makes changes in the database with the new info.
- Creates an output (I use json_encode), that will be read by Ren'Py.

Re: Sample - Using HTTPS to connect to server to transfer game data

Posted: Mon Jan 15, 2018 3:39 pm
by PyTom
I've commented out the second half of xavimat's post, since it looks like it's vulnerable to an SQL injection attack. (At least, I'd need a good argument that it's secure, and I don't see that here - the sanitization for HTML doesn't look like it would protect from SQL injection.)

Re: Sample - Using HTTPS to connect to server to transfer game data

Posted: Mon Jan 15, 2018 5:38 pm
by xavimat
PyTom wrote:
Mon Jan 15, 2018 3:39 pm
I've commented out the second half of xavimat's post, since it looks like it's vulnerable to an SQL injection attack. (At least, I'd need a good argument that it's secure, and I don't see that here - the sanitization for HTML doesn't look like it would protect from SQL injection.)
Thanks, PyTom. I'm sorry, I thought it was enough. I'll learn more about it and correct the file.
I've edited my post to at least explain, without code, what the php file is intended to do.