Skip to content

Commit

Permalink
Merge pull request IonicaBizau#2 from IonicaBizau/statique
Browse files Browse the repository at this point in the history
Use Statique NPM module
  • Loading branch information
IonicaBizau committed Jun 3, 2014
2 parents 193e968 + 83df09a commit 8070049
Show file tree
Hide file tree
Showing 289 changed files with 206,225 additions and 111 deletions.
17 changes: 6 additions & 11 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
# NodeJS Youtube API Test
Test application that tests Youtube API NodeJS module.

## Screenshot
>![](http://i.imgur.com/2B32IcZ.png)
## Before you start

1. You need a [Google Account](https://www.google.com/accounts/NewAccount) to access the Google APIs Console, request an API key, and register your application.
Expand Down Expand Up @@ -50,22 +53,14 @@ provides a simple text representation of arbitrary data structures. For more inf

2. Click **Next** button.
2. Select **Web application** option.
2. Set the **site or hostname** as `localhost:3000`, so the redirect uri will be: `http://localhost:3000/oauth2callback`
2. Set the **site or hostname** as `localhost:5000`, so the redirect uri will be: `http://localhost:5000/oauth2callback`
2. Click **Create client ID** button.
1. Rename `credentials.templ.json` into `credentials.json`.
2. Open `credentials.json` and replace `yourClientId` with the **client id** and `yourSecretKey` with **client secret** generated in the step 10.
2. Now you are ready. Start the script and open `http://localhost:3000`.
2. Now you are ready. Start the script and open `http://localhost:5000`.

```
node index.js
```
## TO-DO

3. ~~Use express to have a better way to access the API.~~
3. ~~More calls to the API with examples.~~

## Examples
- http://localhost:3000/yt/activities = All activities limited to 50 results.
- http://localhost:3000/yt/activities/15 = All activities limited to 15 results.
- http://localhost:3000/yt/activities/after/YYYY-MM-DDThh:mm:ss.sZ = All activities limited to 50 result that where published after the date expecified.
- http://localhost:3000/yt/activities/before/YYYY-MM-DDThh:mm:ss.sZ = All activities limited to 50 result that where published before the date expecified.
Then open `localhost:5000` in your browser and start testing the module.
230 changes: 132 additions & 98 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,111 +1,145 @@
var Youtube = require("youtube-api");
var http = require("http");

var express = require('express'),
yt = require('./routes/yt');

var app = express();
var Youtube = require("youtube-api")
, Http = require("http")
, Statique = require ("statique")
, Http = require('http')
, Request = require("request")
, credentials = require("./credentials")
;

global.ACCESS_TOKEN = undefined;

app.get('/yt/activities/:maxResults', yt.listAllActivities);
app.get('/yt/activities', yt.listAllActivities);
app.get('/yt/activities/after/:date', yt.listActivitiesAfter); //with this format YYYY-MM-DDThh:mm:ss.sZ
app.get('/yt/activities/before/:date', yt.listActivitiesBefore); //with this format YYYY-MM-DDThh:mm:ss.sZ

// You have to provide the credentials, first (in credentials.json file: rename .templ.json into json)
var credentials = require("./credentials");
var request = require("request");

// credentials
credentials.scope = "https://www.googleapis.com/auth/youtube";
credentials.response_type = "code";
credentials.access_type = "offline";

app.get('/',function(req, res){

var authUrl = "https://accounts.google.com/o/oauth2/auth?";

for (var key in credentials) {
console.log(key, credentials[key]);
if (key === "client_secret") { continue; }

authUrl += "&" + key + "=" + credentials[key];
}
if (typeof ACCESS_TOKEN == "undefined") {
var html = "Click <a href='" + authUrl + "'>here</a> to get the access token.";
} else {
var html = "You can call this REStfull links:";
html += "<br><ul><li>/yt/activities = All activities limited to 50 results.</li>";
html += "<li>/yt/activities/15 = All activities limited to 15 results.</li>";
html += "<li>/yt/activities/after/YYYY-MM-DDThh:mm:ss.sZ = All activities limited to 50 result that where published after the date expecified.</li>";
html += "<li>/yt/activities/before/YYYY-MM-DDThh:mm:ss.sZ = All activities limited to 50 result that where published before the date expecified.</li></ul>";
html += "<br>Click <a href='/yt/activities'>here</a> to see the list of all activities. (/yt/activities)";
}
res.setHeader("Content-Type", "text/html");
res.end(html);
return;
});

app.get('/oauth2callback',function(req, res) {
var url = req.url;

if (url.indexOf("error") !== -1) {
return res.end("Error.");
}

if (url.indexOf("?code=") === -1) {
return res.end("Invalid request.");
}

var code = url;
code = code.substring(code.indexOf("?code=") + 6);

if (!code) {
return res.end("Code is missing.");
}

var formData = "code=" + code +
"&client_id=" + credentials.client_id +
"&client_secret=" + credentials.client_secret +
"&redirect_uri=" + credentials.redirect_uri +
"&grant_type=authorization_code";

var options = {
url: "https://accounts.google.com/o/oauth2/token",
headers: {'content-type' : 'application/x-www-form-urlencoded'},
method: "POST",
body: formData
};

request(options, function (err, response, body) {

if (err) {
return res.end(err);
}

try {
body = JSON.parse(body);
} catch (e) {
return res.end(e.message + " :: " + body);
// statique config
Statique
.server({root: __dirname + "/public"})
.setRoutes({
"/": function (req, res) {
if (ACCESS_TOKEN) {
return Statique.readFile("/html/index.html", function (err, content) {
Statique.sendRes(res, 400, "text/html", content);
});
}

var authUrl = "https://accounts.google.com/o/oauth2/auth?";

for (var key in credentials) {
console.log(key, credentials[key]);
if (key === "client_secret") { continue; }

authUrl += "&" + key + "=" + credentials[key];
}

res.writeHead(302, {
"Location": authUrl
});
res.end();
return;
}
if (body.error) {
return res.end(err || body.error);
, "/api/run_code": function (req, res) {

var formData = ""
, error = ""
;

req.on("data", function (data) {
formData += data;
});

req.on("error", function (data) {
error += data;
});

req.on("end", function (data) {

if (error) {
return Statique.sendRes(res, 400, "text/html", error);
}

global.__api_run_code_callback = function (err, data) {
if (err) {
return Statique.sendRes(res, 400, "text", JSON.stringify(err));
}
return Statique.sendRes(res, 200, "text/json", JSON.stringify(data, null, 2));
};

formData = formData.replace("_CALLBACK", "__api_run_code_callback");
try {
eval(formData);
} catch (e) {
return Statique.sendRes(res, 400, "text", e.message);
}
});
}

// success
if (body.access_token) {
ACCESS_TOKEN = body.access_token;
var html = "Click <a href='/'>here</a> to go back.</br> Access token: " + ACCESS_TOKEN;
res.setHeader("Content-Type", "text/html");
return res.end(html);
, "/oauth2callback": function (req, res) {
var url = req.url;

if (url.indexOf("error") !== -1) {
return res.end("Error.");
}

if (url.indexOf("?code=") === -1) {
return res.end("Invalid request.");
}

var code = url;
code = code.substring(code.indexOf("?code=") + 6);

if (!code) {
return res.end("Code is missing.");
}

var formData = "code=" + code +
"&client_id=" + credentials.client_id +
"&client_secret=" + credentials.client_secret +
"&redirect_uri=" + credentials.redirect_uri +
"&grant_type=authorization_code";

var options = {
url: "https://accounts.google.com/o/oauth2/token",
headers: {'content-type' : 'application/x-www-form-urlencoded'},
method: "POST",
body: formData
};

Request(options, function (err, response, body) {

if (err) {
return res.end(err);
}

try {
body = JSON.parse(body);
} catch (e) {
return res.end(e.message + " :: " + body);
}
if (body.error) {
return res.end(err || body.error);
}

// success
if (body.access_token) {
ACCESS_TOKEN = body.access_token;
res.writeHead(302, {
"Location": "/"
});
res.end();
}

return res.end("Something wrong: \n" + JSON.stringify(body, null, 4));
});
}
})
;

return res.end("Something wrong: \n" + JSON.stringify(body, null, 4));
});

return;
});

app.listen(5000);
// create server
Http.createServer(function(req, res) {
Statique.serve (req, res);
}).listen(5000);

// output
console.log("Open: http://localhost:5000");

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@
],
"main": "index.js",
"dependencies": {
"express": "^4.3.1",
"request": "^2.36.0",
"youtube-api": "^0.2.2"
"youtube-api": "^0.2.2",
"statique": "^0.1.1"
},
"devDependencies": {},
"scripts": {
Expand Down
Loading

0 comments on commit 8070049

Please sign in to comment.