Help making tutorial apps

Your other questions have I think been answered. This is set by the application which uses RemoteStorage.JS code - hence not in the repo sorry (although I think it is documented in the comments). Here’s an example use:

    // SAFE Network backend requires application identity and required permissions rather than
    // API keys (authentication is handled by the user via SAFE Launcher, not a server)
    remoteStorage.setApiKeys('safestore', 
        {    
            // For details see SAFE Launcher /auth JSON API
            app: {
                name: 'RemoteStorage Demo',        // Your app name etc.
                version: '0.0.1',
                vendor: 'remoteStorage',
                id: 'org.remotestorage.rsdemo'    // Identifies stored data (unique per vendor)
            },
            permissions: ['SAFE_DRIVE_ACCESS']  // List of permissions to request. On authorisation, 
                                                // holds permissions granted by user
        }

As you can see it is pretty much what is asked for by /auth in the SAFE API.

3 Likes

Yeah I’ve been reading up on ajax and the xhttp functions. I think one could use that to send the information over http to the api. What I’m wondering is how to correctly send and receive. I haven’t done a lot of work using http before, using javascript or otherwise, so a lot of this is new to me.

Also I’m wondering even if one gets the data how does one say input it into a database properly. Questions questions.

    … to send the information over http to the api.

Had s sneak peek, this is from the Safe Network API docs, if you want something done, how to send it off, with specified parameters. Not longwinded at any rate:

request.post(endPoint, {  
  json: true,
  body: payload
}, onResponse);

Stay tuned, more later. Maybe we have a time zone between us?

yes but remember that’s written in node.js and while node is derived from javascript I’m not sure how much is still valid in regular javascript.

Yes we probably o have a timezone between us. I’m on Pacific Time, GMT -8, if that helps.

    node.js <=> regular javascript

So what to use, Node or regular JS to approach the Safe API? I had a chance to try the two “auth”-examples in the API-documentation under Node just now.

More or less cut-and-pasted the first one and the Launcher started to balk already, for me to authorize a newcomer to the scene. Take returned token from the ‘console’ to the other MaidSafe code-fragment and this checked ‘OK’ for “still authorized”.

Coaxing Node into cooperating was the real hurdle. It already sat on my Windows-machine, installed by another application, otherwise there is this download of a single Node.exe as an alternative to a full installation.

If you opt for the single executable you do have to find out how to install other extras yourself but one can have Node married to this wonderful companion, NPM, which then will do all the shopping for you afterwards.

NPM assisted for example when Node wanted ‘request’ to be present to execute the Safe API code to delegate an HTTP-POST and -GET.

About the latter, you had an earlier question answered in the forum I noticed today?

And it is what they say it is, that much less JavaScript to accomplish what you want is a compelling reason to invest in what do IT-books call it, “Mastering this or that”, in this instance Node.

So where are we?

– Our intention to collaborate together pays of nicely - at least for me for now ;o)

– You probably still wish us to explore the pure JavaScript-way of doing things which is OK by me

– Because I will counter with a Windows-scripting initiative which is different from JS

– We’ll have to keep an eye on this other part of the forum where they discuss the future of the Launcher as to not have the rug pulled from under us

– We have to compare notes in regard to what we use for OS and how you want to proceed, was yours in fact an API-question or a general learning-more-of-programming-question?

I’m looking into using ajax and the xhttp functions there but I’m not sure exactly how to send and receive the json information that is supposedly sent back to the user over http. ajax seems to only have a function to receive text or xml so I’m not quite sure how to handle that or corretly convert it into a json file.

My code shows how to do this, example:

var response = JSON.parse(xhr.responseText);
    
          // Save session info
          self.configure({ 
              token:                response.token,        // Auth token
              permissions:          response.permissions,  // List of permissions approved by the user
            });
1 Like

    using ajax and the xhttp functions

What about forgetting JSON for a moment and start with going into the air trying to reach the Safe Launcher (loaded and authorized)?

Did where you was give you example code for using this ‘XMLHttpRequest’ with JS? If not, in your case you just want a minimal HTML-page which harbors the Javascript for sending and receiving.

For instance “Step 3 – A Simple Example” here at developer.mozilla.org probably will do it.

The guiding principle of this REST-thing @dirvine pointed us to: whatever you want to ask from the Launcher is immediately obvious because of the endpoint selected by you, no need for an additional specification of your intentions.

Why the earlier browser experiment for ‘/auth’ did work.

And that’s why we can simply repeat the experiment this time coming from a bit of Javascript, we’re not going to give the Launcher anything but just the absolute bare minimum of a call (HTTP GET Request) and see if it reacts to it.

To do this we have to copy the code and surround it with code for an HTML-skeleton page:

<!DOCTYPE html>
<html>
<body>

   Step 3 - Example code from the link above goes here

</body>
</html>

One change to that example is necessary, where the code should go once set in motion, so here the original:

makeRequest('test.html');

Is adapted to address the Launcher on our PC like so:

makeRequest('http://localhost:8100/auth');

So what do you say, yes? And if you also did copy that specific example does it look like what I have?

1 Like

You need JSON as its part of the API and part of how the API sends the token information back to you.

This is horrible grammar to the point I’m not understanding what you’re saying. Also on SAFE inline scripts are disabled.

Do you mind explaining what exactly your code does? What exactly does var response = JSON.parse(xhr.responseText); do? More specifically xhr.responseText ? Does one prepare code assuming they know what the response will be?

I am having the same kind of trouble/confusion with the API stuff @Blindsite2k.

What I would love to see is a HTML/CSS/JS example of a simple launcher authorization for a “Hello World” type setup. I believe codepen even will allow interactive embedded pens on discourse…maybe that is something that can be part of the dev forum too in a bit!

1 Like

Time out …

It will use JSON, trust me - if we keep it up, this week ;o)

The Mozilla sample or what, my description of what it does?

But how about its purpose? This is not THE app, it’s a few simple steps aimed at getting the bulb switched on. As it were.

Will happily use anything else you provide, because at this stage we should try to get something working, not do everything by the book. Would this ever morph into a real tutorial then there is ample opportunity to get everything else right?

As you know that could easily be remedied later on in any code you write later:

 <script src="./scripts.js"></script>

Then again, this is a simple experiment, us trying to access the Safe Network programmatically for the first time, nothing else.

How do you see it double back later from the other end on the Safe network?

True, there are concerns about accessing the Safe Launcher from outside the PC it sits on but at this stage you should not worry too much, this thread is titled “Help making tutorial apps development”.

So, show me yours :sunglasses:

Guys can we move this thread to the new Dev Forum?

It seems like a perfect fit, as it would be incredibly useful to new devs looking on there

EDIT: just made a thread myself. Join & discuss!

Are you sure? Got a slightly different impression as to what its purpose was meant to be. And moving or continuing this there?

JSON.parse() is a standard library function so you can look it up but essentially you give it some text that is in JSON format and it returns a JavaScript object equivalent to that structured text (ie with the same members and values).

So for example, a structure/object expressed as text in JSON format such as:

{
   body: "foo",
   metadata: "bar"
}

Pass that to JSON.parse() and it would return an object with members “body” that has value “foo”, and “metadata” that has value “bar”.

var mything = JSON.parse(’{
body: “foo”,
metadata: “bar”
}’):

returns an object so you do:

alert(mything.body);

And it would display a message box with the text “foo”.

Hope that helps.

EDIT:

Does one prepare code assuming they know what the response will be?

One tests for all possible responses and handles then accordingly. If you look at my code you’ll see this.

2 Likes

What’s the xht?

But I think I get what you’re saying. To get the individual componants of the JSON passed back from the API, since we know what is expected from the API, we can parse the response into it’s componant parts using JSON.parse() and then reference the individual isolated components. So correct me if I’m wrong but to isolate the token from the response returned by the API would look something like this.

//Declare variables
var endpoint = 'http://localhost:8100/auth';
var endpointLongname = 'http://localhost:8100/dns/safenetwork';
var response = xhttp.responseText;
var payload = {
  "app": {
    "name":"Hello World",
    "id":"Hello World Alpha 1",
    "version":"0.0.1",
    "vendor":"Blindsite"
  },
  "permissions": [
    "SAFE_DRIVE_ACCESS"
  ]
};
var responseParsed = JSON.parse(response);
var apitoken = responseParsed.token;
var apipermissions = responseParsed.permissions;

//Check to see if the user has a token aka status 200.
//I'm wondering if or how to get the first user ID in the list?  That is how does one get one's Public ID?
if (xhttp.status == 200) {
    xhttp.open("GET", endpointLongname.apitoken, true);
    xhttp.send();
    document.write("<p>Hello World!  Hello, " + response + "!</p>");
} else if (xhttp.status == 400 || 401) {
    // Attempt to get a token.
    xhttp.open("POST", endpoint.payload, true);
    xhttp.send();
} else {
    document.write("<p>Authentication Failed.</p>")
}

I’m sure there are a lot of mistakes. But that’s what this is all about. Find the bugs and correct them.

2 Likes

Your getting there David, I know this can feel like eating a dessert :wink: but there is an oasis - actually many of them - to help you on your way and I think you’re approaching one right now.

You have the order back to front above because the status indicates whether or not the request succeeded, and therefore whether you have been given a token to decode.

So look at my code and try to understand that, and then fix your code above. You’ll see I’m checking the status code before I try to decode the response text.

I think you’ve got the essentials now so reading code will start to get a bit easier if you can skip over bits you don’t fully understand yet and fill in those blanks only as needed.

At least that’s my approach: learn as little as I can get away with while I’m getting going, and only when I feel ready do I dive into the more complex stuff.

There’s still stuff in that file that I don’t understand - one reason there is code there commented out is when I modify something I tend to leave the earlier version in place in case it stops working and only delete it when I’m sure what I have is doing what I intended. Later I’ll clean it all up, but for now it’s a work in progress, a scratchpad for my own use rather than code that’s ready to share (sorry about that :slight_smile: but I still thought it was close enough to what you needed from what’s available).

1 Like

I created this basic demo to give an idea on how to make an API call. You can find it here: http://simplesafe.safeguard.safenet/ (alpha network)

First press the authorize button to get a valid token. Then you can post, get and delete a file.

I kept the code as straight forward as possible to make it easy to understand. So there is no jquery, no promises, no css and even no constants. Each function (post(), get() and remove()) are self contained so there is a lot of redundancy but it shows at a quick glance what’s needed to make the API call.

Open the dev console to see the response you get from the server.

Hope this help.

index.html
simple_safe.js

8 Likes

Should we all, as a community, finally start putting our links here in proper safe:// form?

Possibly flagging people’s links that are still in the old .safenet form?

Wondering how much we should do to enforce the decision we’ve made for proper safe:// formatting.

I’d love to see this happen

1 Like

All hail Emporor @whiteoutmashups introducing tyrany to SAFE 1 link at a time. I didn’t agree to use safe://, or declare i was going to switch over to the safe browser, nor do I think anyone should be penalized for using .safenet. My god man people have a choice as to what apps they use and what protocols they code with. Who said what was proper or not? safe:// is only functional on the safe browser and it’s not even built yet. If you start flagging posts for being in .safenet i’ll be flagging posts because they’re in safe:// and not in .safenet.

4 Likes

lol you’re crazy dude.

good point, about the current state of development,

but be ready for this to happen eventually.

1 Like