Browse Source

cleanup of handler.js

version-14
Rushabh Mehta 13 years ago
parent
commit
370b9e473e
18 changed files with 247 additions and 463 deletions
  1. +14
    -10
      js/core.min.js
  2. +1
    -5
      js/legacy/app.js
  3. +20
    -40
      js/legacy/jquery/jquery-ui.min.js
  4. +1
    -65
      js/legacy/utils/dom.js
  5. +36
    -156
      js/legacy/utils/handler.js
  6. +0
    -48
      js/legacy/webpage/freeze_page.js
  7. +21
    -0
      js/legacy/webpage/spinner.js
  8. +1
    -1
      js/legacy/widgets/dialog.js
  9. +1
    -1
      js/legacy/widgets/form/form_comments.js
  10. +1
    -1
      js/legacy/widgets/tabbedpage.js
  11. +5
    -1
      js/legacy/widgets/tags.js
  12. +12
    -6
      js/wn/assets.js
  13. +7
    -7
      js/wn/dom.js
  14. +111
    -0
      js/wn/request.js
  15. +2
    -2
      js/wn/ui/button.js
  16. +0
    -66
      js/wn/xmlhttp.js
  17. +13
    -54
      py/webnotes/auth.py
  18. +1
    -0
      py/webnotes/boot.py

+ 14
- 10
js/core.min.js View File

@@ -12,13 +12,6 @@ if(!window.wn)wn={}
wn.provide=function(namespace){var nsl=namespace.split('.');var l=nsl.length;var parent=window;for(var i=0;i<l;i++){var n=nsl[i];if(!parent[n]){parent[n]={}}
parent=parent[n];}}
wn.provide('wn.settings');wn.provide('wn.ui');
/*
* lib/js/wn/xmlhttp.js
*/
wn.xmlhttp={request:function(){if(window.XMLHttpRequest)
return new XMLHttpRequest();else if(window.ActiveXObject)
return new ActiveXObject("MsXml2.XmlHttp");},complete:function(req,callback,url){if(req.status==200||req.status==304){callback(req.responseText);}else{alert(url+' request error: '+req.statusText+' ('+req.status+')');}},get:function(url,callback,args,async){if(async===null)async=true;var req=wn.xmlhttp.request();req.onreadystatechange=function(){if(req.readyState==4){wn.xmlhttp.complete(req,callback,url)}}
var sep=((args&&args.indexOf('?'))==-1)?'?':'&';var u=args?(url+sep+args):url;req.open('GET',u,async);req.send(null);if(!async){wn.xmlhttp.complete(req,callback,url)}}}
/*
* lib/js/wn/versions.js
*/
@@ -30,7 +23,7 @@ localStorage.setItem('_version_number',window._version_number);}}}
*/
wn.assets={executed_:{},exists:function(src){if('localStorage'in window&&localStorage.getItem(src))
return true},add:function(src,txt){if('localStorage'in window){localStorage.setItem(src,txt);}},get:function(src){return localStorage.getItem(src);},extn:function(src){if(src.indexOf('?')!=-1){src=src.split('?').slice(-1)[0];}
return src.split('.').slice(-1)[0];},load:function(src){var t=src;wn.xmlhttp.get(t,function(txt){wn.assets.add(src,txt);},'q='+Math.floor(Math.random()*1000),false)},execute:function(src){if(!wn.assets.exists(src)){wn.assets.load(src);}
return src.split('.').slice(-1)[0];},load:function(src){var t=src;$.ajax({url:t,data:{q:Math.floor(Math.random()*1000)},dataType:'text',success:function(txt){wn.assets.add(src,txt);},async:false})},execute:function(src){if(!wn.assets.exists(src)){wn.assets.load(src);}
var type=wn.assets.extn(src);if(wn.assets.handler[type]){wn.assets.handler[type](wn.assets.get(src),src);wn.assets.executed_[src]=1;}},handler:{js:function(txt,src){wn.dom.eval(txt);},css:function(txt,src){var se=document.createElement('style');se.type="text/css";if(se.styleSheet){se.styleSheet.cssText=txt;}else{se.appendChild(document.createTextNode(txt));}
document.getElementsByTagName('head')[0].appendChild(se);},cgi:function(txt,src){wn.dom.eval(txt)}}}
/*
@@ -50,8 +43,7 @@ else
c.className=className;}
if(cs)wn.dom.css(c,cs);if(innerHTML)c.innerHTML=innerHTML;if(onclick)c.onclick=onclick;return c;}
wn.dom.css=function(ele,s){if(ele&&s){for(var i in s)ele.style[i]=s[i];};return ele;}
wn.dom.hide=function(ele){ele.style.display='none';}
wn.dom.show=function(ele,value){if(!value)value='block';ele.style.display=value;}
wn.get_cookie=function(c){var t=""+document.cookie;var ind=t.indexOf(c);if(ind==-1||c=="")return"";var ind1=t.indexOf(';',ind);if(ind1==-1)ind1=t.length;return unescape(t.substring(ind+c.length+1,ind1));}
/*
* lib/js/wn/page.js
*/
@@ -96,6 +88,18 @@ text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}}());
/*
* lib/js/wn/request.js
*/
wn.provide('wn.request');wn.request.url='index.cgi';wn.request.prepare=function(opts){if(opts.btn)$(opts.btn).set_working();if(opts.show_spinner)set_loading();if(opts.freeze)freeze();if(!opts.args.cmd){console.log(opts)
throw"Incomplete Request";}}
wn.request.cleanup=function(opts,r){if(opts.btn)$(opts.btn).done_working();if(opts.show_spinner)hide_loading();if(opts.freeze)unfreeze();if(wn.boot.sid&&wn.get_cookie('sid')!=wn.boot.sid){msgprint('Session expired');setTimeout('redirect_to_login()',3000);return;}
if(r.server_messages)msgprint(r.server_messages)
if(r.exc){errprint(r.exc);console.log(r.exc);};if(r.docs)LocalDB.sync(r.docs);}
wn.request.call=function(opts){wn.request.prepare(opts);$.ajax({url:opts.url||wn.request.url,data:opts.args,type:opts.type||'POST',dataType:opts.dataType||'json',success:function(r,xhr){wn.request.cleanup(opts,r);opts.success(r,xhr.responseText);},error:function(xhr,textStatus){wn.request.cleanup(opts,{});msgprint('Unable to complete request: '+textStatus)
if(opts.error)opts.error(xhr)}})}
wn.call=function(opts){var args=opts.args||{};if(opts.module&&opts.page){args.cmd=module+'.page.'+page+'.'+page+'.'+method}else if(opts.method){args.cmd=opts.method;}
wn.request.call({args:args,success:opts.callback,error:opts.error,btn:opts.btn,freeze:opts.freeze,show_spinner:!opts.no_spinner});}
/*
* lib/js/core.js
*/


+ 1
- 5
js/legacy/app.js View File

@@ -3,13 +3,9 @@
// dialog container
var popup_cont;
var session = {};
var start_sid = null;
if(!wn) var wn = {};

function startup() {
// save the sid (so that we know if it changes mid-session)
start_sid = get_cookie('sid');
function startup() {
popup_cont = $a(document.getElementsByTagName('body')[0], 'div');

// Globals


+ 20
- 40
js/legacy/jquery/jquery-ui.min.js
File diff suppressed because it is too large
View File


+ 1
- 65
js/legacy/utils/dom.js View File

@@ -272,12 +272,9 @@ function $i(id) {
if(id && id.appendChild)return id; // already an element
return document.getElementById(id);
}
function $t(parent, txt) { if(parent.substr)parent = $i(parent); return parent.appendChild(document.createTextNode(txt)); }
function $w(e,w) { if(e && e.style && w)e.style.width = w; }
function $h(e,h) { if(e && e.style && h)e.style.height = h; }
function $bg(e,w) { if(e && e.style && w)e.style.backgroundColor = w; }
function $fg(e,w) { if(e && e.style && w)e.style.color = w; }
function $op(e,w) { if(e && e.style && w) { set_opacity(e,w); } }

function $y(ele, s) {
if(ele && s) {
@@ -415,16 +412,6 @@ function get_scroll_top() {
return st;
}


function get_cookie(c) {
var t=""+document.cookie;
var ind=t.indexOf(c);
if (ind==-1 || c=="") return "";
var ind1=t.indexOf(';',ind);
if (ind1==-1) ind1=t.length;
return unescape(t.substring(ind+c.length+1,ind1));
}

// URL utilities

wn.urllib = {
@@ -474,55 +461,4 @@ wn.urllib = {
}

get_url_arg = wn.urllib.get_arg;
get_url_dict = wn.urllib.get_dict;

// set user image
var user_img = {}
var user_img_queue = {};
var user_img_loading = [];

set_user_img = function(img, username, get_latest, img_id) {
function set_it(i) {
if(user_img[username]=='no_img_m')
i.src = 'lib/images/ui/no_img_m.gif';
else if(user_img[username]=='no_img_f')
i.src = 'lib/images/ui/no_img_f.gif'; // no image
else {
ac_id = wn.control_panel.account_id;
i.src = repl('cgi-bin/getfile.cgi?ac=%(ac)s&name=%(fn)s', {fn:user_img[username], ac:ac_id});
}
}

// given
if(img_id) {
user_img[username] = img_id;
set_it(img);
return;
}
// from dict or load
if(user_img[username] && !get_latest) {
set_it(img);
} else{
// queue multiple request while loading
if(in_list(user_img_loading,username)) {
if(!user_img_queue[username])
user_img_queue[username] = [];
user_img_queue[username].push(img);
return;
}
$c('webnotes.profile.get_user_img',{username:username},function(r,rt) {
delete user_img_loading[user_img_loading.indexOf(username)];
user_img[username] = r.message;

if(user_img_queue[username]) {
var q=user_img_queue[username];
for(var i in q) { set_it(q[i]); }
}
set_it(img);
}, null, 1);
user_img_loading.push(username);
}

}
get_url_dict = wn.urllib.get_dict;

+ 36
- 156
js/legacy/utils/handler.js View File

@@ -20,146 +20,50 @@
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

// My HTTP Request

var outUrl = "index.cgi";
var NULL_CHAR = '^\5*';

// check response of HTTP request, only if ready
function checkResponse(r, on_timeout, no_spinner, freeze_msg) {
try {
if (r.readyState==4 && r.status==200) return true; else return false;
} catch(e) {
// $i("icon_loading").style.visibility = "hidden"; WAINING MESSAGE
msgprint("error:Request timed out, try again");
if(on_timeout)
on_timeout();

hide_loading();

if(freeze_msg)
unfreeze();
return false;
}
}

var pending_req = 0;

// new XMLHttpRequest object
function newHttpReq() {
if (!$.browser.msie)
var r=new XMLHttpRequest();
else if (window.ActiveXObject)
var r=new ActiveXObject("Microsoft.XMLHTTP");
return r;
}

// call execute serverside request
function $c(command, args, fn, on_timeout, no_spinner, freeze_msg, btn) {
var req=newHttpReq();
ret_fn=function() {
if (checkResponse(req, on_timeout, no_spinner, freeze_msg)) {
if(btn)$(btn).done_working();
if(!no_spinner)
hide_loading(); // Loaded

var rtxt = req.responseText;
try {
var r = JSON.parse(rtxt);
} catch(e) {
msgprint('Handler Exception:' + rtxt);
return;
}
// unfreeze
if(freeze_msg)unfreeze();
if(!validate_session(r,rtxt)) return;
if(r.exc) {
errprint(r.exc);
console.log(r.exc);
};
if(r.server_messages) { msgprint(r.server_messages);};
if(r.docs) { LocalDB.sync(r.docs); }
saveAllowed = true;
if(fn)fn(r, rtxt);
}
}
if(btn) $(btn).set_working();
req.onreadystatechange=ret_fn;
req.open("POST",outUrl,true);
req.setRequestHeader("ENCTYPE", "multipart/form-data");
req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
args['cmd']=command;
req.send(makeArgString(args));
if(!no_spinner)set_loading(); // Loading
if(freeze_msg)freeze(freeze_msg,1);
}

function validate_session(r,rt) {
// check for midway change in session
if(r.message=='Logged In') {
start_sid = get_cookie('sid');
return true;
}
if(start_sid && start_sid != get_cookie('sid') && user && user!='Guest') {
page_body.set_session_changed();
return;
}

// check for expired session
if(r.exc && r.session_status=='Session Expired') {
resume_session();
return;
}

// check for logged out sesion
if(r.exc && r.session_status=='Logged Out') {
msgprint('You have been logged out');
setTimeout('redirect_to_login()', 3000);
return;
}
if(r.exc && r.exc_type && r.exc_type=='PermissionError') {
loadpage('_home');
}
return true;
function $c(command, args, callback, error, no_spinner, freeze_msg, btn) {
wn.request.call({
args: $.extend(args, {cmd: command}),
success: callback,
error: error,
btn: btn,
freeze: freeze_msg,
show_spinner: !no_spinner
})
}

// For calling an object
function $c_obj(doclist, method, arg, call_back, no_spinner, freeze_msg, btn) {
var args = { 'method':method, 'arg': (typeof arg=='string' ? arg : JSON.stringify(arg)) }
if(typeof doclist=='string') args.doctype = doclist;
else args.docs = compress_doclist(doclist)

// single
$c('runserverobj',args, call_back, null, no_spinner, freeze_msg, btn);
function $c_obj(doclist, method, arg, callback, no_spinner, freeze_msg, btn) {
if(typeof arg=='string') arg = JSON.stringify(arg);
wn.request.call({
args: {
cmd:'runserverobj',
arg: arg,
method: method
},
success: callback,
btn: btn,
freeze: freeze_msg,
show_spinner: !no_spinner
});
}

// For call a page metho
function $c_page(module, page, method, arg, call_back, no_spinner, freeze_msg, btn) {
if(arg && !arg.substr) arg = JSON.stringify(arg);
$c(module+'.page.'+page+'.'+page+'.'+method,{'arg':arg},
call_back, null, no_spinner, freeze_msg, btn);
}

// generic server call (call page, object)
wn.call = function(args) {
if(!args.args) args.args = {};
if(args.module && args.page) {
$c_page(args.module, args.page, args.method, args.args, args.callback,
args.no_spinner, false, args.btn);
} else if(args.docs) {
$c_obj(args.doc, args.method, args.args, args.callback, args.no_spinner,
false, args.btn);
} else {
$c(args.method, args.args, args.callback, false, args.no_spinner, false, args.btn);
}
function $c_page(module, page, method, arg, callback, no_spinner, freeze_msg, btn) {
if(typeof arg=='string') arg = JSON.stringify(arg);
wn.request.call({
args: {
cmd: module+'.page.'+page+'.'+page+'.'+method,
arg: arg,
method: method
},
success: callback,
error: error,
btn: btn,
freeze: freeze_msg,
show_spinner: !no_spinner
});
}


// For calling an for output as csv
function $c_obj_csv(doclist, method, arg) {
// single
@@ -179,30 +83,6 @@ function $c_obj_csv(doclist, method, arg) {
open_url_post(outUrl, args);
}

function my_eval(co) {
var w = window;

// Evaluate script
if (!w.execScript) {
if (/Gecko/.test(navigator.userAgent)) {
eval(co, w); // Firefox 3.0
} else {
eval.call(w, co);
}
} else {
w.execScript(co); // IE
}
}

function makeArgString(dict) {
var varList = [];

for(key in dict){
varList[varList.length] = key + '=' + encodeURIComponent(dict[key]);
}
return varList.join('&');
}

// call a url as POST
function open_url_post(URL, PARAMS, new_window) {
var temp=document.createElement("form");


+ 0
- 48
js/legacy/webpage/freeze_page.js View File

@@ -1,48 +0,0 @@
// Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
//
// MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

var fcount = 0;
var frozen = 0;
var dialog_message;
var dialog_back;

function freeze(msg, do_freeze) {
// blur
if(!dialog_back) {
dialog_back = $a($i('body_div'), 'div', 'dialog_back');
$(dialog_back).css('opacity', 0.6);
}
$ds(dialog_back);

fcount++;
frozen = 1;
}
function unfreeze() {
if(dialog_message)
$dh(dialog_message);
if(!fcount)return; // anything open?
fcount--;
if(!fcount) {
$dh(dialog_back);
frozen = 0;
}
}

+ 21
- 0
js/legacy/webpage/spinner.js View File

@@ -20,6 +20,10 @@
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

var pending_req = 0;
var fcount = 0;
var dialog_back;

function set_loading() {
pending_req++;
$('#spinner').css('visibility', 'visible');
@@ -32,4 +36,21 @@ function hide_loading() {
$('body').css('cursor', 'default');
$('#spinner').css('visibility', 'hidden');
}
}

function freeze() {
// blur
if(!dialog_back) {
dialog_back = $a($i('body_div'), 'div', 'dialog_back');
$(dialog_back).css('opacity', 0.6);
}
$ds(dialog_back);
fcount++;
}
function unfreeze() {
if(!fcount)return; // anything open?
fcount--;
if(!fcount) {
$dh(dialog_back);
}
}

+ 1
- 1
js/legacy/widgets/dialog.js View File

@@ -75,7 +75,7 @@ Dialog.prototype.make_row = function(d) {
var c1 = $td(t,0,0);
var c2 = $td(t,0,1);
if(d[0]!='Check' && d[0]!='Button')
$t(c1, d[1]);
$(c1).text(d[1]);
}
if(d[0]=='HTML') {


+ 1
- 1
js/legacy/widgets/form/form_comments.js View File

@@ -176,7 +176,7 @@ CommentItem = function(cell, ri, ci, d, comment) {
// Set picture
// -----------
CommentItem.prototype.set_picture = function(d, ri){
set_user_img(this.img, user)
this.user.src = wn.user_info(d[ri][2]).image;
this.cmt_by.innerHTML = d[ri][7] ? d[ri][7] : d[ri][2];
}



+ 1
- 1
js/legacy/widgets/tabbedpage.js View File

@@ -63,7 +63,7 @@ TabbedPage.prototype.add_tab = function(n, onshow, no_body, with_heading) {
tab.set_selected = function() {
if(me.cur_tab) me.cur_tab.collapse();
this.className = 'box_tab_selected';
$op(this, 100);
$(this).css('opacity', 1);
me.cur_tab = this;
}
tab.expand = function(arg) {


+ 5
- 1
js/legacy/widgets/tags.js View File

@@ -225,7 +225,11 @@ SingleTag.prototype.make_body = function(parent) {
if(this.onclick) $y(this.body, {cursor:'pointer'});
// hover
$(this.body).hover(function() { $op(this,60); } ,function() { $op(this,100); });
$(this.body).hover(function() {
$(this).css('opacity', 0.6);
} ,function() {
$(this).css('opacity', 1);
});

// label
this.make_label();


+ 12
- 6
js/wn/assets.js View File

@@ -22,7 +22,6 @@

// library to mange assets (js, css, models, html) etc in the app.
// will try and get from localStorge if latest are available
// or will load them via xmlhttp
// depends on wn.versions to manage versioning

wn.assets = {
@@ -57,16 +56,23 @@ wn.assets = {
},
// load an asset via
// xmlhttp
load: function(src) {
// this is virtual page load, only get the the source
// *without* the template
var t = src;

wn.xmlhttp.get(t, function(txt) {
// add it to localstorage
wn.assets.add(src, txt);
}, 'q=' + Math.floor(Math.random()*1000) , false)
$.ajax({
url: t,
data: {
q: Math.floor(Math.random()*1000)
},
dataType: 'text',
success: function(txt) {
// add it to localstorage
wn.assets.add(src, txt);
},
async: false
})
},
// pass on to the handler to set


+ 7
- 7
js/wn/dom.js View File

@@ -61,11 +61,11 @@ wn.dom.css= function(ele, s) {
return ele;
}

wn.dom.hide = function(ele) {
ele.style.display = 'none';
}
wn.dom.show = function(ele, value) {
if(!value) value = 'block';
ele.style.display = value;
wn.get_cookie = function(c) {
var t=""+document.cookie;
var ind=t.indexOf(c);
if (ind==-1 || c=="") return "";
var ind1=t.indexOf(';',ind);
if (ind1==-1) ind1=t.length;
return unescape(t.substring(ind+c.length+1,ind1));
}

+ 111
- 0
js/wn/request.js View File

@@ -0,0 +1,111 @@
// Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
//
// MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

// My HTTP Request

wn.provide('wn.request');
wn.request.url = 'index.cgi';

// call execute serverside request
wn.request.prepare = function(opts) {
// btn indicator
if(opts.btn) $(opts.btn).set_working();
// navbar indicator
if(opts.show_spinner) set_loading();
// freeze page
if(opts.freeze) freeze();
// no cmd?
if(!opts.args.cmd) {
console.log(opts)
throw "Incomplete Request";
}
}

wn.request.cleanup = function(opts, r) {
// stop button indicator
if(opts.btn) $(opts.btn).done_working();
// hide button indicator
if(opts.show_spinner) hide_loading();

// un-freeze page
if(opts.freeze) unfreeze();

// session expired?
if(wn.boot.sid && wn.get_cookie('sid') != wn.boot.sid) {
msgprint('Session expired');
setTimeout('redirect_to_login()', 3000);
return;
}
// show messages
if(r.server_messages) msgprint(r.server_messages)
// show errors
if(r.exc) { errprint(r.exc); console.log(r.exc); };
// sync docs
if(r.docs) LocalDB.sync(r.docs);
}

wn.request.call = function(opts) {
wn.request.prepare(opts);
$.ajax({
url: opts.url || wn.request.url,
data: opts.args,
type: opts.type || 'POST',
dataType: opts.dataType || 'json',
success: function(r, xhr) {
wn.request.cleanup(opts, r);
opts.success(r, xhr.responseText);
},
error: function(xhr, textStatus) {
wn.request.cleanup(opts, {});
msgprint('Unable to complete request: ' + textStatus)
if(opts.error)opts.error(xhr)
}
})
}

// generic server call (call page, object)
wn.call = function(opts) {
var args = opts.args || {};
// cmd
if(opts.module && opts.page) {
args.cmd = module+'.page.'+page+'.'+page+'.'+method
} else if(opts.method) {
args.cmd = opts.method;
}

wn.request.call({
args: args,
success: opts.callback,
error: opts.error,
btn: opts.btn,
freeze: opts.freeze,
show_spinner: !opts.no_spinner
});
}

+ 2
- 2
js/wn/ui/button.js View File

@@ -56,7 +56,7 @@ wn.ui.Button = function(args) {
if(me.btn.args.is_ajax) {
$(me.btn).css('margin-right', '0px');
}
wn.dom.show(me.loading_img, 'inline');
$(me.loading_img).css('display','inline');
},
done_working: function() {
@@ -64,7 +64,7 @@ wn.ui.Button = function(args) {
if(me.btn.args.is_ajax) {
$(me.btn).css('margin-right', '24px');
}
wn.dom.hide(me.loading_img);
$(me.loading_img).toggle(false);
}
});
this.make();


+ 0
- 66
js/wn/xmlhttp.js View File

@@ -1,66 +0,0 @@
// Copyright (c) 2012 Web Notes Technologies Pvt Ltd (http://erpnext.com)
//
// MIT License (MIT)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

wn.xmlhttp = {
request: function() {
if ( window.XMLHttpRequest ) // Gecko
return new XMLHttpRequest() ;
else if ( window.ActiveXObject ) // IE
return new ActiveXObject("MsXml2.XmlHttp") ;
},
complete: function(req, callback, url) {
if (req.status==200 || req.status==304) {
callback(req.responseText);
} else {
alert(url +' request error: ' + req.statusText + ' (' + req.status + ')' ) ;
}
},
get: function(url, callback, args, async) {
// async by default
if(async === null) async=true;
var req = wn.xmlhttp.request();
// for async type
req.onreadystatechange = function() {
if (req.readyState==4) {
wn.xmlhttp.complete(req, callback, url)
}
}
// separator can be & or ?
// based on if there are already arguments
var sep = ((args && args.indexOf('?'))==-1) ? '?' : '&';
// add arguments to url
var u = args ? (url + sep + args) : url;

// call the server
req.open('GET', u, async);
req.send(null);
// for sync
if(!async) {
wn.xmlhttp.complete(req, callback, url)
}
}
}

+ 13
- 54
py/webnotes/auth.py View File

@@ -62,11 +62,6 @@ class HTTPRequest:
webnotes.msgprint(webnotes.conn.get_global("__session_status_message"))
raise webnotes.SessionStopped('Session Stopped')


# write out cookies if sid is supplied (this is a pre-logged in redirect)
if webnotes.form_dict.get('sid'):
webnotes.cookie_manager.set_cookies()

# run login triggers
if webnotes.form_dict.get('cmd')=='login':
webnotes.login_manager.run_trigger('on_login_post_session')
@@ -74,6 +69,9 @@ class HTTPRequest:
# load profile
self.setup_profile()

# write out cookies
webnotes.cookie_manager.set_cookies()

webnotes.conn.commit()
# end transaction
# -----------------------------
@@ -305,7 +303,6 @@ class CookieManager:
# sid expires in 3 days
import datetime
expires = datetime.datetime.now() + datetime.timedelta(days=3)

webnotes.cookies['sid']['expires'] = expires.strftime('%a, %d %b %Y %H:%M:%S')

# Set Remember Me
@@ -345,36 +342,19 @@ class Session:
r = webnotes.conn.sql("""select user, sessiondata, status from
tabSessions where sid='%s'""" % self.sid)
if not r:
# return guest record if present
self.sid = 'Guest'
r = webnotes.conn.sql("""select user, sessiondata, status from
tabSessions where sid='%s'""" % self.sid)
return r
return r and r[0] or None
def load(self):
"""non-login request: load a session"""
import webnotes
r = self.get_session_record()
if r:
r=r[0]
# ExipredSession
if r[2]=='Expired' and (webnotes.form_dict.get('cmd')!='resume_session'):
if r[0]=='Guest' or (not webnotes.form_dict.get('cmd')) or webnotes.form_dict.get('cmd')=='logout':
self.start_as_guest()
else:
webnotes.response['session_status'] = 'Session Expired'
raise Exception, 'Session Expired'
elif r[2]=='Logged Out':
self.start_as_guest()
# allow refresh or logout
if webnotes.form_dict.get('cmd') and webnotes.form_dict.get('cmd')!='logout':
webnotes.response['session_status'] = 'Logged Out'
raise Exception, 'Logged Out'
else:
self.data = {'data': (r[1] and eval(r[1]) or {}),
self.data = {'data': (r[1] and eval(r[1]) or {}),
'user':r[0], 'sid': self.sid}
else:
self.start_as_guest()
@@ -384,9 +364,8 @@ class Session:
webnotes.login_manager.login_as_guest()
self.start()

# start a session
# ---------------
def start(self):
"""start a new session"""
import os
import webnotes
import webnotes.utils
@@ -417,33 +396,13 @@ class Session:
raise e

# update profile
webnotes.conn.sql("UPDATE tabProfile SET last_login = '%s', last_ip = '%s' where name='%s'" % (webnotes.utils.now(), webnotes.remote_ip, self.data['user']))
webnotes.conn.sql("""UPDATE tabProfile SET last_login = '%s', last_ip = '%s'
where name='%s'""" % (webnotes.utils.now(), webnotes.remote_ip, self.data['user']))

# set cookies to write
webnotes.session = self.data
webnotes.cookie_manager.set_cookies()


# resume session
# --------------
def resume(self):
pwd = webnotes.form_dict.get('pwd')
webnotes.login_manager.authenticate(self.data['user'], pwd)
webnotes.conn.sql("update tabSessions set status='Active' where sid=%s", self.data['sid'])
return 'Logged In'
# update session
# --------------
def update(self):
# update session
if webnotes.session['user'] != 'Guest':
webnotes.conn.sql("""update tabSessions set sessiondata=%s, user=%s, lastupdate=NOW()
where sid=%s""" , (str(self.data['data']), self.data['user'], self.data['sid']))

self.check_expired()

# check expired
# -------------
def check_expired(self):
"""expire non-guest sessions"""
exp_sec = webnotes.conn.get_value('Control Panel', None, 'session_expiry') or '6:00:00'
@@ -460,8 +419,6 @@ class Session:
webnotes.conn.sql("""delete from tabSessions where TIMEDIFF(NOW(), lastupdate)
> '72:00:00' and sid!='Guest'""")

# Get IP Info from ipinfodb.com
# -----------------------------
def get_ipinfo(self):
import os
@@ -473,7 +430,9 @@ class Session:
gi = pygeoip.GeoIP('data/GeoIP.dat')
self.data['data']['ipinfo'] = {'countryName': gi.country_name_by_addr(os.environ.get('REMOTE_ADDR'))}
# -----------------------------
def insert_session_record(self):
webnotes.conn.sql("insert into tabSessions (sessiondata, user, lastupdate, sid, status) values (%s , %s, NOW(), %s, 'Active')", (str(self.data['data']), self.data['user'], self.data['sid']))
webnotes.conn.sql("""insert into tabSessions
(sessiondata, user, lastupdate, sid, status)
values (%s , %s, NOW(), %s, 'Active')""",
(str(self.data['data']), self.data['user'], self.data['sid']))

+ 1
- 0
py/webnotes/boot.py View File

@@ -52,6 +52,7 @@ def get_bootinfo():
import webnotes.widgets.menus
bootinfo['dt_labels'] = get_dt_labels()
bootinfo['user_info'] = get_fullnames()
bootinfo['sid'] = webnotes.session['sid'];
# home page
get_home_page(bootinfo, doclist)


Loading…
Cancel
Save