From 21378495e60c18deb8f96980d3e095892ad48f5b Mon Sep 17 00:00:00 2001 From: coderaiser Date: Sun, 18 Nov 2012 07:36:16 -0500 Subject: [PATCH] throw out jquery from github module, moved Cache object to client --- ChangeLog | 4 + client.js | 92 +++-------------------- lib/client/dom.js | 78 +++++++++++++++++--- lib/client/storage/_github.js | 133 ++++++++++++++++++++-------------- 4 files changed, 157 insertions(+), 150 deletions(-) diff --git a/ChangeLog b/ChangeLog index 2136ace2..7918c960 100644 --- a/ChangeLog +++ b/ChangeLog @@ -100,6 +100,10 @@ right panel. * Fixed bug with context menu. Now it disabled before load menu module to. +* Throw out jquery from github module, moved Cache +object from client to DOM module, +refactored Cache object and added polyfill. + 2012.10.01, Version 0.1.7 diff --git a/client.js b/client.js index 7191b9b5..8755285d 100644 --- a/client.js +++ b/client.js @@ -28,8 +28,6 @@ var CloudClient = { * загружает содержимое каталогов */ /* ОБЬЕКТЫ */ - /* Обьект для работы с кэшем */ - Cache : {}, /* ПРИВАТНЫЕ ФУНКЦИИ */ /* функция загружает json-данные о файловой системе */ @@ -109,78 +107,6 @@ var loadModule = function(pParams){ }; }; -/** - * Обьект для работы с кэшем - * в него будут включены функции для - * работы с LocalStorage, webdb, - * indexed db etc. - */ -CloudClient.Cache = { - _allowed : true, /* приватный переключатель возможности работы с кэшем */ - - /* функция проверяет возможно ли работать с кэшем каким-либо образом */ - isAllowed : function(){}, - - /* Тип кэша, который доступен*/ - type : {}, - - /* Функция устанавливает кэш, если выбранный вид поддерживаеться браузером*/ - set :function(){}, - - /* Функция достаёт кэш, если выбранный вид поддерживаеться браузером*/ - get : function(){}, - - /* функция чистит весь кэш для всех каталогов*/ - clear : function(){} -}; - - -/** функция проверяет поддерживаеться ли localStorage */ -CloudClient.Cache.isAllowed = (function(){ - if(window.localStorage && - localStorage.setItem && - localStorage.getItem){ - CloudClient.Cache._allowed=true; - }else - { - CloudClient.Cache._allowed=false; - /* загружаем PolyFill для localStorage, - * если он не поддерживаеться браузером - * https://gist.github.com/350433 - */ - /* - DOM.jsload('https://raw.github.com/gist/350433/c9d3834ace63e5f5d7c8e1f6e3e2874d477cb9c1/gistfile1.js', - function(){CloudClient.Cache._allowed=true; - }); - */ - } -}); - - /** если доступен localStorage и - * в нём есть нужная нам директория - - * записываем данные в него - */ -CloudClient.Cache.set = function(pName, pData){ - if(CloudClient.Cache._allowed && pName && pData){ - localStorage.setItem(pName,pData); - } -}; - -/** Если доступен Cache принимаем из него данные*/ -CloudClient.Cache.get = function(pName){ - if(CloudClient.Cache._allowed && pName){ - return localStorage.getItem(pName); - } - else return null; -}; - -/** Функция очищает кэш */ -CloudClient.Cache.clear = function(){ - if(CloudClient.Cache._allowed){ - localStorage.clear(); - } -}; - CloudClient.GoogleAnalytics = function(){ /* google analytics */ var lFunc = document.onmousemove; @@ -480,7 +406,7 @@ function initKeysPanel(pCallBack){ } function baseInit(pCallBack){ - if(applicationCache){ + if(applicationCache){ var lFunc = applicationCache.onupdateready; applicationCache.onupdateready = function(){ @@ -508,10 +434,10 @@ function baseInit(pCallBack){ cloudcmd._changeLinks(CloudFunc.RIGHTPANEL); /* устанавливаем переменную доступности кэша */ - cloudcmd.Cache.isAllowed(); + DOM.Cache.isAllowed(); /* Устанавливаем кэш корневого каталога */ - if(!cloudcmd.Cache.get('/')) - cloudcmd.Cache.set('/', cloudcmd._getJSONfromFileTable()); + if( !DOM.Cache.get('/') ) + DOM.Cache.set('/', cloudcmd._getJSONfromFileTable()); }); /* устанавливаем размер высоты таблицы файлов @@ -536,7 +462,7 @@ function baseInit(pCallBack){ var lHeight = window.screen.height; lHeight = lHeight - (lHeight/3).toFixed(); - lHeight = (lHeight/100).toFixed()*100; + lHeight = (lHeight / 100).toFixed() * 100; cloudcmd.HEIGHT = lHeight; @@ -569,7 +495,7 @@ CloudClient._changeLinks = function(pPanelID){ /* назначаем кнопку очистить кэш и показываем её */ var lClearcache = getById('clear-cache'); if(lClearcache) - lClearcache.onclick = CloudClient.Cache.clear; + lClearcache.onclick = DOM.Cache.clear; /* меняем ссылки на ajax-запросы */ var lPanel = getById(pPanelID), @@ -736,9 +662,9 @@ CloudClient._ajaxLoad = function(path, pNeedRefresh){ lError; if(pNeedRefresh === undefined && lPanel){ - var lJSON = CloudClient.Cache.get(lPath); + var lJSON = DOM.Cache.get(lPath); - if (lJSON !== null){ + if (lJSON){ /* переводим из текста в JSON */ if(window && !window.JSON){ lError = Util.tryCatchLog(function(){ @@ -784,7 +710,7 @@ CloudClient._ajaxLoad = function(path, pNeedRefresh){ * сохраняем их в кэше */ if(lJSON_s.length<50000) - CloudClient.Cache.set(lPath,lJSON_s); + DOM.Cache.set(lPath,lJSON_s); } }); }); diff --git a/lib/client/dom.js b/lib/client/dom.js index 92fe7211..93d1e810 100644 --- a/lib/client/dom.js +++ b/lib/client/dom.js @@ -119,22 +119,21 @@ var CloudCommander, $, Util, DOM, CloudFunc; * load file countent thrue ajax */ DOM.ajax = function(pParams){ - /* if on webkit */ + var lType = pParams.type || 'GET', + lData = pParams.data, + lSuccess_f = pParams.success; + if(!XMLHTTP) - XMLHTTP = new XMLHttpRequest(); + XMLHTTP = new XMLHttpRequest(); - var lMethod = 'GET'; - if(pParams.method) - lMethod = pParams.method; + XMLHTTP.open(lType, pParams.url, true); + XMLHTTP.send(lData); - XMLHTTP.open(lMethod, pParams.url, true); - XMLHTTP.send(null); - - var lSuccess_f = pParams.success; if( !Util.isFunction(lSuccess_f) ) - console.log('error in DOM.ajax onSuccess:', pParams); + console.log('error in DOM.ajax onSuccess:', pParams) && + console.log(pParams); - XMLHTTP.onreadystatechange = function(pEvent){ + XMLHTTP.onreadystatechange = function(pEvent){ if (XMLHTTP.readyState === 4 /* Complete */){ var lJqXHR = pEvent.target, lType = XMLHTTP.getResponseHeader('content-type'); @@ -166,8 +165,63 @@ var CloudCommander, $, Util, DOM, CloudFunc; } } }; - }; + }; + + /** + * Обьект для работы с кэшем + * в него будут включены функции для + * работы с LocalStorage, webdb, + * indexed db etc. + */ + DOM.Cache = function(){ + /* приватный переключатель возможности работы с кэшем */ + var CacheAllowed, + Data = {}; + /* функция проверяет возможно ли работать с кэшем каким-либо образом */ + this.isAllowed = function(){ + return ( CacheAllowed = Util.isObject( window.localStorage ) ); + }; + + /** remove element */ + this.remove = function(pItem){ + return CacheAllowed ? + localStorage.removeItem(pItem) : + (delete Data[pItem]); + }; + + /** если доступен localStorage и + * в нём есть нужная нам директория - + * записываем данные в него + */ + this.set = function(pName, pData){ + var lRet; + + if(pName && pData) + lRet = CacheAllowed ? + localStorage.setItem(pName,pData) : + Data[pName] = pData; + + return lRet; + }, + + /** Если доступен Cache принимаем из него данные*/ + this.get = function(pName){ + return CacheAllowed ? + localStorage.getItem(pName) : + Data[pName]; + }, + + /** функция чистит весь кэш для всех каталогов*/ + this.clear = function(){ + return CacheAllowed ? + localStorage.clear() : + (Data = {}); + }; + }; + + DOM.Cache = new DOM.Cache(); + /** * Function gets id by src * @param pSrc diff --git a/lib/client/storage/_github.js b/lib/client/storage/_github.js index b76aedb6..be1b2396 100644 --- a/lib/client/storage/_github.js +++ b/lib/client/storage/_github.js @@ -1,4 +1,5 @@ -var CloudCommander, Util, DOM, $, Github; +var CloudCommander, Util, DOM, $, Github, cb; + /* temporary callback function for work with github */ /* module for work with github */ (function(){ @@ -6,12 +7,17 @@ var CloudCommander, Util, DOM, $, Github; var cloudcmd = CloudCommander, + API_URL = '/api/v1/auth', CLIENT_ID, - CLIENT_SECRET, + Cache = DOM.Cache, + GitHub, + User, GithubStore = {}; cloudcmd.Storage = {}; - + + cb = function (err, data){ console.log(err || data);} + /* PRIVATE FUNCTIONS */ /** @@ -38,19 +44,23 @@ var CloudCommander, Util, DOM, $, Github; cloudcmd.loadConfig(function(){ var lConfig = cloudcmd.Config; CLIENT_ID = lConfig.oauth_client_id; - CLIENT_SECRET = lConfig.oauth_client_secret; Util.exec(pCallBack); }); } - function callback(pError, pData){ - console.log(pError || pData); + function saveToken(pToken){ + return Cache.set('token', pToken); } + function getToken(){ + return Cache.get('token'); + } + + /* PUBLICK FUNCTIONS */ GithubStore.basicLogin = function(pUser, pPasswd){ - cloudcmd.Storage.Github = new Github({ + cloudcmd.Storage.Github = GitHub = new Github({ username: pUser, password: pPasswd, auth : 'basic' @@ -58,66 +68,79 @@ var CloudCommander, Util, DOM, $, Github; }; GithubStore.Login = function(pToken){ - cloudcmd.Storage.Github = new Github({ + cloudcmd.Storage.Github = Github = new Github({ token : pToken, auth : 'oauth' }); - }; - - function init(){ - var lCode = window.location.search; - if ( Util.isContainStr(lCode, '?code=') ){ - lCode = lCode.replace('?code=',''); - - $.ajax({ - type:'put', - url:'/api/v1/auth', - data: lCode, - success: function(pData){ - var lToken = pData.token; - - if(pData){ - GithubStore.Login(lToken); - - getUserData(lToken); - } - } - }); - } - else - cloudcmd.Auth(); - } - - cloudcmd.Auth = function(){ - window.location = - 'https://github.com/login/oauth/authorize?client_id=' + - CLIENT_ID + '&&scope=repo,user,gist'; + + User = Github.getUser(); }; - function getUserData(pToken){ - var lHelloFunc = function(pData){ - var lName; - if(pData) - lName = ' ' + pData.name ; - - console.log('Hello' + lName + ' :)!'); - }; + function init(pCallBack){ + var lToken = getToken(); + if(lToken){ + GithubStore.Login(lToken); + Util.exec(pCallBack); + } + else{ + var lCode = window.location.search; + if ( Util.isContainStr(lCode, '?code=') ){ + lCode = lCode.replace('?code=',''); + + DOM.ajax({ + type : 'put', + url : API_URL, + data: lCode, + success: function(pData){ + if(pData && pData.token){ + lToken = pData.token; + + GithubStore.Login(lToken); + saveToken(lToken); + Util.exec(pCallBack); + } + else + Util.log("Worning: token not getted..."); + } + }); + } + else + window.location = + 'https://github.com/login/oauth/authorize?client_id=' + + CLIENT_ID + '&&scope=repo,user,gist'; + } + } + + function getUserData(){ + var lShowRepos = function(pError, pRepos){ + Util.log('Repositories: '); + if(!pError) + for(var i = 0, n = pRepos.length; i < n ; i++) + console.log(pRepos[i].name); + else + DOM.Cache.remove('token'); + }, - if(pToken) - $.ajax({ - url : 'https://api.github.com/user?access_token=' + pToken, - success : lHelloFunc - }); - else - lHelloFunc(); + lShowUserInfo = function(pError, pData){ + if(!pError){ + console.log('Hello ' + pData.name + ' :)!'); + User.repos(lShowRepos); + } + else + DOM.Cache.remove('token'); + }; + + + User.show(null, lShowUserInfo); } cloudcmd.Storage.Keys = function(){ - DOM.jqueryLoad( Util.retLoadOnLoad([ + Util.loadOnLoad([ + getUserData, init, setConfig, load - ])); + ]); }; cloudcmd.Storage.GithubStore = GithubStore;