Commit 4ca7ca1b by Иван Кубота

auth through js api

parent 76daf9f9
var data = require('./skus.json');
var getters = {
"EYESHADOW": function(item) {
var colors = item.colors;
return [item.skuType, item.skuNo, colors[0].colorCode, colors[0].glossIntensity, colors[0].shimmerColorCode, colors[0].shimmerIntensity]
},
"LIPCOLOR": function(item) {
var colors = item.colors;
return [item.skuType, item.skuNo, colors[0].colorCode, colors[0].glossIntensity, colors[0].shimmerColorCode, colors[0].shimmerIntensity]
},
"EYELINER": function(item) {
var colors = item.colors;
return [item.skuType, item.skuNo, colors[0].colorCode, colors[0].glossIntensity, colors[0].shimmerColorCode, colors[0].shimmerIntensity]
}
};
var cols = ['Type', 'SKU ID', 'Color', 'Gloss %', 'Shimmer Color', 'Shimmer %'];
var fs = require('fs');
fs.writeFile('skus.csv',
cols.join(',')+'\n'+
data.results.map(item=> getters[item.skuType](item).join(',')).join('\n'),function(){
});
\ No newline at end of file
<!DOCTYPE html>
<html>
<head>
<title>Google Sheets API Quickstart</title>
<meta charset="utf-8" />
</head>
<body>
<p>Google Sheets API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" style="display: none;">Authorize</button>
<button id="signout_button" style="display: none;">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = "838942638829-3koe535vg4adclpd01sd3nnmi250h2ra.apps.googleusercontent.com";
var API_KEY = "AIzaSyD13Vbl1iq36HFABoVa27-VcOyqSMYNTZw";//"AIzaSyDx2DNm9fX9VXh6YzKEg5JybYSE6A6dZLg";
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://sheets.googleapis.com/$discovery/rest?version=v4"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/spreadsheets.readonly";
var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listMajors();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* @param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
function listMajors() {
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: '1EkUKPUf2uedFd55lUj4_LQOb1EUXfcN8j96KU1qTy3w',
range: 'SKU!A2:F',
}).then(function(response) {
debugger
var range = response.result;
if (range.values.length > 0) {
appendPre('Name, Major:');
for (i = 0; i < range.values.length; i++) {
var row = range.values[i];
// Print columns A and E, which correspond to indices 0 and 4.
appendPre(row[0] + ', ' + row[4]);
}
} else {
appendPre('No data found.');
}
}, function(response) {
appendPre('Error: ' + response.result.error.message);
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
\ No newline at end of file
...@@ -4,6 +4,11 @@ License: MPL 2.0 ...@@ -4,6 +4,11 @@ License: MPL 2.0
Contact: zibx@quokka.pub Contact: zibx@quokka.pub
*/ */
/*
Observable Store based in 2016 April by Ivan Kubota
License: MPL 2.0
Contact: zibx@quokka.pub
*/
const isEqual = function(original, fn) { const isEqual = function(original, fn) {
return function(val) { return function(val) {
fn(val===original); fn(val===original);
...@@ -14,6 +19,13 @@ const isContain = function(original, fn) { ...@@ -14,6 +19,13 @@ const isContain = function(original, fn) {
fn((val||[]).indexOf(original)>-1); fn((val||[]).indexOf(original)>-1);
} }
}; };
/*
-- DESIGN --
Store MUST notify all subscribers on each change
Store MUST NOT notify subscribers if it does not change
*/
const Store = function(cfg) { const Store = function(cfg) {
Observable.call(this); Observable.call(this);
this.events = new Observable(); this.events = new Observable();
...@@ -99,14 +111,21 @@ Store.prototype = { ...@@ -99,14 +111,21 @@ Store.prototype = {
setParent: function(parent, key, item){ setParent: function(parent, key, item){
this.parent = new StoreParent(parent, key, item); this.parent = new StoreParent(parent, key, item);
}, },
bindings: function() {
var out = {};
for(var k in this._props){
out[k] = this.bind(k);
}
return out;
},
item: function(key, item){ item: function(key, item){
let subStore = new Store(item?item:key); let subStore = new Store(item?item:key);
subStore.setParent(this, key, item); subStore.setParent(this, key, item);
return subStore; return subStore;
}, },
array: function(key){ array: function(key){
let arrayStore = new ArrayStore(this.get(key)) let arrayStore = new ArrayStore(this.get(key));
arrayStore.setParent(this, key) arrayStore.setParent(this, key);
return arrayStore; return arrayStore;
}, },
experimental: false, experimental: false,
...@@ -235,14 +254,34 @@ Store.prototype = { ...@@ -235,14 +254,34 @@ Store.prototype = {
sub: function(key, fn, suppresFirstCall) { sub: function(key, fn, suppresFirstCall) {
var un; var un;
if(Array.isArray(key)){ if(Array.isArray(key)){
var wrap = () => fn.apply(this, key.map(key=>key instanceof StoreBinding ? key.get() : this.get(key))); var _self = this;
var args = new Array(key.length);
var caller = function() {
return fn.apply(_self, args);
};
var wrap = function(i){
return function(val) {
args[i] = val;
return caller();
};
};
var uns = []; var uns = [];
for( var i = 0, _i = key.length; i < _i; i++ ){ for( var i = 0, _i = key.length; i < _i; i++ ){
if(key[i] instanceof StoreBinding){ if(key[i] instanceof StoreBinding){
uns.push(key[i].sub(wrap)); uns.push(key[i].sub(wrap(i)));
args[i] = key[i].get();
}else if(key[i] instanceof HookPrototype){
uns.push(key[i].hook(wrap(i)));
args[i] = key[i].get();
}else{ }else{
uns.push(this.on( key[ i ], wrap )) uns.push(this.on( key[ i ], wrap(i) ));
args[i] = this.get(key[ i ]);
} }
} }
!suppresFirstCall && wrap(); !suppresFirstCall && wrap();
return function() { return function() {
...@@ -326,6 +365,14 @@ StoreBinding.prototype = { ...@@ -326,6 +365,14 @@ StoreBinding.prototype = {
}, },
bind: function(key) { bind: function(key) {
return new StoreBinding(this.store, this.key+'.'+key); return new StoreBinding(this.store, this.key+'.'+key);
},
hook: function(draw) {
return this.sub(function(val){
draw(val);
});
},
array: function() {
return this.store.array(this.key);
} }
}; };
Store.prototype = Object.assign(new Observable, Store.prototype); Store.prototype = Object.assign(new Observable, Store.prototype);
...@@ -449,7 +496,17 @@ HookPrototype.prototype = { ...@@ -449,7 +496,17 @@ HookPrototype.prototype = {
x.sub = (fn)=> this.hook(fn); x.sub = (fn)=> this.hook(fn);
return x; return x;
}, },
hook: function(fn) { this.subscribers.push(fn); fn(this.get()); }, hook: function(fn) {
this.subscribers.push(fn);
fn(this.get());
var _self = this;
return function() {
var index = _self.subscribers.indexOf(fn);
if(index>-1){
_self.subscribers.splice( index, 1 );
}
}
},
_emit: function(oldVal, val) { _emit: function(oldVal, val) {
var subscribers = this.subscribers; var subscribers = this.subscribers;
for( var i = 0, _i = subscribers.length; i < _i; i++ ){ for( var i = 0, _i = subscribers.length; i < _i; i++ ){
...@@ -470,69 +527,142 @@ var HookFactory = function(accessor) { ...@@ -470,69 +527,142 @@ var HookFactory = function(accessor) {
return Hook; return Hook;
}; };
Store.getValue = function(val) {
if(val instanceof StoreBinding){
return val.hook();
}else{
return val;
}
};
Store.Value = { Store.Value = {
Boolean: new HookFactory({ Boolean: new HookFactory({
setter: function(val) { return !!val; }, setter: function(val) { return !!val; },
toggle: function() { this.set(!this.get()); } toggle: function() { this.set(!this.get()); }
}), }),
Number: new HookFactory({ Number: new HookFactory({
setter: function(val) { return val-0; }
}),
String: new HookFactory({
setter: function(val) { return val+''; }
}),
Integer: new HookFactory({
setter: function(val) { return val|0; } setter: function(val) { return val|0; }
}) }),
Any: new HookFactory(),
Function: new HookFactory()
}; };
Store.HookPrototype = HookPrototype; Store.HookPrototype = HookPrototype;
/*
-- DESIGN --
Array DOES NOT notify the store when it's item changes
Array MUST notify itself when item is added or removed
Array MUST notify when it is reordered
Array Item MUST be observed itself
*/
var getter = function( i ){ return this[i]; };
var fns = Array.prototype;
const ArrayStore = function (cfg) { const ArrayStore = function(cfg) {
Store.call(this, cfg); Store.call(this, cfg);
if( !('get' in this._props) ){
Object.defineProperties( this._props, {
get: { value: getter, enumerable: false }
} );
}
this.length = this._props.length;
}; };
ArrayStore.prototype = { ArrayStore.prototype = {
push: function (val) { length: 0,
var changeList = []; indexOf: function (a) {
changeList.push(['', this._props]) return this._props.indexOf(a);
},
toArray: function () {
return this._props;
},
_fireAdd: function (item, pos) {
var arr = this._props;
this.fire('add', item, pos > 0 ? arr.get(pos-1) : null, pos < this.length - 1 ? arr.get(pos+1) : null, pos)
},
_fireRemove: function (item, pos) {
var arr = this._props;
this.fire('remove', item, pos > 0 ? arr.get(pos-1) : null, pos < this.length ? arr.get(pos) : null, pos)
},
push: function (item) {
// single item push only
var out = this._props.push(item);
this._fireAdd(item, this.length++);
return out;
},
unshift: function (item) {
// single item unshift only
var out = this._props.unshift(item);
this.length++;
this._fireAdd(item, 0);
return out;
},
shift: function(){
var pos = --this.length,
arr = this._props,
item = arr.shift();
this.set(this.getLength(), val, changeList); this._fireRemove(item, 0);
this._notify(changeList); return item;
return this;
}, },
pop: function () { pop: function () {
var changeList = []; var pos = --this.length,
changeList.push(['', this._props]); arr = this._props,
var out = this.get(this.getLength()-1); item = arr.pop();
this.set(this.getLength()-1, void 0, changeList);
this._props.pop(); this._fireRemove(item, pos);
this._notify(changeList); return item;
},
splice: function(start, count){
var i, _i, newItems = fns.slice.call(arguments,2 ), out = [];
for(i = 0;i<count; i++)
out.push(this.remove(start));
for(i = 0, _i = newItems.length; i < _i; i++)
this.insert(newItems[i], i + start);
return out; return out;
}, },
remove: function(item) { /*
var idx = this._props.indexOf(item); set - updates element
if(idx>-1){ @arg pos: position of element. defined on [0..length]
var changeList = []; @arg item: element to set
changeList.push(['', this._props]);
this._props.splice(idx,1); @return element that was in that position before
//this.set(this.getLength()-1, void 0, changeList); */
this._notify(changeList); set: function(pos, item){
if(pos === this.length){
this.push( item );
return void 0; // for same behavior we return empty array
} }
return this; return this.splice(pos, 1, item)[0];
}, },
slice: function () {}, iterator: function(start){
splice: function () {}, return new Iterator(this, start);
getLength: function () {
return this._props.length;
}, },
update: function() { remove: function(pos){
var changeList = []; var item = this._props.splice(pos,1)[0];
changeList.push(['', this._props]); this.length--;
this._notify(changeList); this._fireRemove(item, pos);
return this; return item;
}, },
'~destructor': function() { insert: function(item, pos){
this._listeners = this.events = this._props = null; this._props.splice(pos, 0, item);
this.length++;
this._fireAdd(item, pos)
},
forEach: function (fn) {
return this._props.forEach(fn);
} }
}; };
ArrayStore.prototype = Object.assign(new Store(), ArrayStore.prototype); ArrayStore.prototype = Object.assign(new Store(), ArrayStore.prototype);
typeof module === 'object' && (module.exports = Store); typeof module === 'object' && (module.exports = Store);
(typeof window === 'object') && (window.Store = Store); (typeof window === 'object') && (window.Store = Store);
\ No newline at end of file
...@@ -7,6 +7,8 @@ var colorsFromPoints = function(points, ctx, where, k, production, notThis, part ...@@ -7,6 +7,8 @@ var colorsFromPoints = function(points, ctx, where, k, production, notThis, part
deltaSkin = 8; deltaSkin = 8;
if(partName === 'eyes') if(partName === 'eyes')
deltaSkin = 15; deltaSkin = 15;
if(partName === 'other')
deltaSkin = 4;
var minX = Infinity, minY = Infinity, var minX = Infinity, minY = Infinity,
maxX = -Infinity, maxY = -Infinity; maxX = -Infinity, maxY = -Infinity;
...@@ -227,7 +229,14 @@ var extractColors = function( ctx, where, k, production, notThis, partName){ ...@@ -227,7 +229,14 @@ var extractColors = function( ctx, where, k, production, notThis, partName){
return triangle.apply( null, polygon ); return triangle.apply( null, polygon );
} ) ); } ) );
return colorsFromPoints(points, ctx, where, k, production, notThis, partName); var clrs = colorsFromPoints(points, ctx, where, k, production, notThis, partName);
if(partName === 'blush' && clrs.length === 0){
clrs = colorsFromPoints(points, ctx, where, k, production, notThis, 'other');
if(clrs.length === 0){
clrs = notThis;
}
}
return clrs;
}; };
var colorSort = function(a,b){return (-(a[2]-b[2]))+(-(a[1]-b[1])/2)}; var colorSort = function(a,b){return (-(a[2]-b[2]))+(-(a[1]-b[1])/2)};
var similarColor = 5;//0.05; var similarColor = 5;//0.05;
...@@ -304,6 +313,9 @@ var extractor = function(partName, ctx, from, k, production, notThis) { ...@@ -304,6 +313,9 @@ var extractor = function(partName, ctx, from, k, production, notThis) {
colors = [{color: labToRgb.apply(null, mean), hsv: mean}] colors = [{color: labToRgb.apply(null, mean), hsv: mean}]
} }
if(production !== 0 && production !== void 0){ if(production !== 0 && production !== void 0){
if(partName[0] !== '_' && partName !== 'skin'){
document.getElementById( partName + '-bg' ).style.display = colors.length ? 'block' : 'none';
}
var clrs = document.getElementById(partName+'-bg').querySelector('.colors'); var clrs = document.getElementById(partName+'-bg').querySelector('.colors');
clrs && clrs.parentNode.removeChild(clrs); clrs && clrs.parentNode.removeChild(clrs);
......
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment