-
Notifications
You must be signed in to change notification settings - Fork 11
/
clarifai.js
81 lines (75 loc) · 2.03 KB
/
clarifai.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
function getCredentials(cb) {
var data = {
'grant_type': 'client_credentials',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET
};
var url = 'https://api.clarifai.com/v1/token';
return axios.post(url, data, {
'transformRequest': [
function() {
return transformDataToParams(data);
}
]
}).then(function(r) {
localStorage.setItem('accessToken', r.data.access_token);
localStorage.setItem('tokenTimestamp', Math.floor(Date.now() / 1000));
cb();
}, function(err) {
console.log(err);
});
}
function transformDataToParams(data) {
var str = [];
for (var p in data) {
if (data.hasOwnProperty(p) && data[p]) {
if (typeof data[p] === 'string'){
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(data[p]));
}
if (typeof data[p] === 'object'){
for (var i in data[p]) {
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(data[p][i]));
}
}
}
}
return str.join('&');
}
function postImage(imgurl) {
var accessToken = localStorage.getItem('accessToken');
var data = {
'url': imgurl
};
var url = 'https://api.clarifai.com/v1/tag';
return axios.post(url, data, {
'headers': {
'Authorization': 'Bearer ' + accessToken
}
/*'content-type': 'application/x-www-form-urlencoded'*/
}).then(function(r) {
parseResponse(r.data);
}, function(err) {
console.log('Sorry, something is wrong: ' + err);
});
}
function parseResponse(resp) {
var tags = [];
if (resp.status_code === 'OK') {
var results = resp.results;
tags = results[0].result.tag.classes;
} else {
console.log('Sorry, something is wrong.');
}
document.getElementById('tags').innerHTML = tags.toString().replace(/,/g, ', ');
return tags;
}
function run(imgurl) {
if (Math.floor(Date.now() / 1000) - localStorage.getItem('tokenTimeStamp') > 86400
|| localStorage.getItem('accessToken') === null) {
getCredentials(function() {
postImage(imgurl);
});
} else {
postImage(imgurl);
}
}