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

Discuss how to use the Ren'Py engine to create visual novels and story-based games. New releases are announced in this section.
Forum rules
This is the right place for Ren'Py help. Please ask one question per thread, use a descriptive subject like 'NotFound error in option.rpy' , and include all the relevant information - especially any relevant code and traceback messages. Use the code tag to format scripts.
Post Reply
Message
Author
cookienomnom
Newbie
Posts: 15
Joined: Thu Jan 11, 2018 10:02 am
Contact:

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

#1 Post 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!!

User avatar
Imperf3kt
Lemma-Class Veteran
Posts: 3792
Joined: Mon Dec 14, 2015 5:05 am
itch: Imperf3kt
Location: Your monitor
Contact:

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

#2 Post 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
Warning: May contain trace amounts of gratuitous plot.
pro·gram·mer (noun) An organism capable of converting caffeine into code.

Current project: GGD Mentor

Twitter

User avatar
PyTom
Ren'Py Creator
Posts: 16096
Joined: Mon Feb 02, 2004 10:58 am
Completed: Moonlight Walks
Projects: Ren'Py
IRC Nick: renpytom
Github: renpytom
itch: renpytom
Location: Kings Park, NY
Contact:

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

#3 Post by PyTom »

Right now, the most complete example is on my patreon, here:

https://www.patreon.com/posts/news-from-your-15636026
Supporting creators since 2004
(When was the last time you backed up your game?)
"Do good work." - Virgil Ivan "Gus" Grissom
Software > Drama • https://www.patreon.com/renpytom

cookienomnom
Newbie
Posts: 15
Joined: Thu Jan 11, 2018 10:02 am
Contact:

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

#4 Post 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!!!

User avatar
PyTom
Ren'Py Creator
Posts: 16096
Joined: Mon Feb 02, 2004 10:58 am
Completed: Moonlight Walks
Projects: Ren'Py
IRC Nick: renpytom
Github: renpytom
itch: renpytom
Location: Kings Park, NY
Contact:

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

#5 Post 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.)
Supporting creators since 2004
(When was the last time you backed up your game?)
"Do good work." - Virgil Ivan "Gus" Grissom
Software > Drama • https://www.patreon.com/renpytom

User avatar
xavimat
Eileen-Class Veteran
Posts: 1461
Joined: Sat Feb 25, 2012 8:45 pm
Completed: Yeshua, Jesus Life, Cops&Robbers
Projects: Fear&Love
Organization: Pilgrim Creations
Github: xavi-mat
itch: pilgrimcreations
Location: Spain
Discord: xavimat
Contact:

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

#6 Post 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.
Last edited by xavimat on Mon Jan 15, 2018 5:36 pm, edited 1 time in total.
Comunidad Ren'Py en español: ¡Únete a nuestro Discord!
Rhaier Kingdom A Ren'Py Multiplayer Adventure Visual Novel.
Cops&Robbers A two-player experiment | Fear&Love Why can't we say I love you?
Honest Critique (Avatar made with Chibi Maker by ~gen8)

User avatar
PyTom
Ren'Py Creator
Posts: 16096
Joined: Mon Feb 02, 2004 10:58 am
Completed: Moonlight Walks
Projects: Ren'Py
IRC Nick: renpytom
Github: renpytom
itch: renpytom
Location: Kings Park, NY
Contact:

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

#7 Post 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.)
Supporting creators since 2004
(When was the last time you backed up your game?)
"Do good work." - Virgil Ivan "Gus" Grissom
Software > Drama • https://www.patreon.com/renpytom

User avatar
xavimat
Eileen-Class Veteran
Posts: 1461
Joined: Sat Feb 25, 2012 8:45 pm
Completed: Yeshua, Jesus Life, Cops&Robbers
Projects: Fear&Love
Organization: Pilgrim Creations
Github: xavi-mat
itch: pilgrimcreations
Location: Spain
Discord: xavimat
Contact:

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

#8 Post 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.
Comunidad Ren'Py en español: ¡Únete a nuestro Discord!
Rhaier Kingdom A Ren'Py Multiplayer Adventure Visual Novel.
Cops&Robbers A two-player experiment | Fear&Love Why can't we say I love you?
Honest Critique (Avatar made with Chibi Maker by ~gen8)

Post Reply

Who is online

Users browsing this forum: No registered users