[FiX] added OAuth , google account login through OAuth

bzr revid: pga@tinyerp.com-20130509141001-s9gtsdfnwxlgvsls
This commit is contained in:
Parth Gajjar (Open ERP) 2013-05-09 19:40:01 +05:30
parent 2c6aeae911
commit 32352d0695
5 changed files with 204 additions and 175 deletions

View File

@ -27,7 +27,10 @@
'category': 'Tools',
'installable': True,
'auto_install': False,
'js': ['static/src/js/gdocs.js'],
'js': [
'static/lib/gapi/client.js',
'static/src/js/gdocs.js',
],
# 'qweb': ['static/src/xml/gdocs.xml'],
'data': [
'security/ir.model.access.csv',
@ -36,7 +39,7 @@
'demo': [
'google_docs_demo.xml'
],
'depends': ['google_base_account','crm'],
'depends': ['crm'],
'description': """
Integrate Google document with OpenERP.
=======================================

View File

@ -28,92 +28,9 @@ from urlparse import urlparse
_logger = logging.getLogger(__name__)
try:
import gdata.docs.data
import gdata.docs.client
# API breakage madness in the gdata API - those guys are insane.
try:
# gdata 2.0.15+
gdata.docs.client.DocsClient.copy_resource
except AttributeError:
# gdata 2.0.14- : copy_resource() was copy()
gdata.docs.client.DocsClient.copy_resource = gdata.docs.client.DocsClient.copy
try:
# gdata 2.0.16+
gdata.docs.client.DocsClient.get_resource_by_id
except AttributeError:
try:
# gdata 2.0.15+
gdata.docs.client.DocsClient.get_resource_by_self_link
def get_resource_by_id_2_0_16(self, resource_id, **kwargs):
return self.GetResourceBySelfLink(
gdata.docs.client.RESOURCE_FEED_URI + ('/%s' % resource_id), **kwargs)
gdata.docs.client.DocsClient.get_resource_by_id = get_resource_by_id_2_0_16
except AttributeError:
# gdata 2.0.14- : alias get_resource_by_id()
gdata.docs.client.DocsClient.get_resource_by_id = gdata.docs.client.DocsClient.get_doc
try:
import atom.http_interface
_logger.info('GData lib version `%s` detected' % atom.http_interface.USER_AGENT)
except (ImportError, AttributeError):
_logger.debug('GData lib version could not be detected', exc_info=True)
except ImportError:
_logger.warning("Please install latest gdata-python-client from http://code.google.com/p/gdata-python-client/downloads/list")
class google_docs_ir_attachment(osv.osv):
_inherit = 'ir.attachment'
def _auth(self, cr, uid, context=None):
'''
Connexion with google base account
@return client object for connexion
'''
#pool the google.login in google_base_account
google_pool = self.pool.get('google.login')
#get gmail password and login. We use default_get() instead of a create() followed by a read() on the
# google.login object, because it is easier. The keys 'user' and 'password' ahve to be passed in the dict
# but the values will be replaced by the user gmail password and login.
user_config = google_pool.default_get(cr, uid, {'user' : '' , 'password' : ''}, context=context)
#login gmail account
client = google_pool.google_login(user_config['user'], user_config['password'], type='docs_client', context=context)
if not client:
raise osv.except_osv(_('Google Drive Error!'), _("Check your google account configuration in Users/Users/Google Account."))
_logger.info('Logged into google docs as %s', user_config['user'])
return client
def copy_gdoc(self, cr, uid, res_model, res_id, name_gdocs, gdoc_template_id, context=None):
'''
copy an existing document in google docs
:param res_model: the object for which the google doc is created
:param res_id: the Id of the object for which the google doc is created
:param name_gdocs: the name of the future ir.attachment that will be created. Based on the google doc template foun.
:param gdoc_template_id: the id of the google doc document to copy
:return: the ID of the google document object created
'''
#login with the base account google module
client = self._auth(cr, uid)
# fetch and copy the original document
try:
doc = client.get_resource_by_id(gdoc_template_id)
#copy the document you choose in the configuration
copy_resource = client.copy_resource(doc, name_gdocs)
except:
raise osv.except_osv(_('Google Drive Error!'), _("Your resource id is not correct. You can find the id in the google docs URL."))
# create an ir.attachment
self.create(cr, uid, {
'res_model': res_model,
'res_id': res_id,
'type': 'url',
'name': name_gdocs,
'url': copy_resource.get_alternate_link().href
}, context=context)
return copy_resource.resource_id.text
def get_google_docs_config(self, cr, uid, res_model, res_id, context=None):
'''
Function called by the js, when no google doc are yet associated with a record, with the aim to create one. It
@ -157,39 +74,37 @@ class google_docs_ir_attachment(osv.osv):
record_ids = model.search(cr, uid, domain, context=ctx)
return record_ids
def get_google_attachment(self, cr, uid, config_id, res_id, context=None):
pool_gdoc_config = self.pool.get('google.docs.config')
class config(osv.osv):
_name = 'google.docs.config'
_description = "Google Drive templates config"
def get_google_doc_name(self, cr, uid, ids, res_id, context=None):
pool_model = self.pool.get("ir.model")
attachment = {'url': False}
config = pool_gdoc_config.browse(cr, SUPERUSER_ID, config_id, context=context)
if config:
res = {}
for config in self.browse(cr, SUPERUSER_ID, ids, context=context):
res_model = config.model_id
model_ids = pool_model.search(cr, uid, [('model','=',res_model)])
if not model_ids:
return attachment
model = pool_model.browse(cr, uid, model_ids[0], context=context).name
continue
model = pool_model.browse(cr, uid, model_ids[0], context=context)
model_name = model.name
filter_name = config.filter_id and config.filter_id.name or False
record = self.pool.get(res_model).read(cr, uid, res_id, [], context=context)
record.update({'model': model,'filter':filter_name})
record.update({'model': model_name,'filter':filter_name})
name_gdocs = config.name_template or "%(name)s_%(model)s_%(filter)s_gdrive"
try:
name_gdocs = name_gdocs % record
except:
raise osv.except_osv(_('Key Error!'), _("Your Google Doc Name Pattern's key does not found in object."))
attach_ids = self.search(cr, uid, [('res_model','=',res_model),('name','=',name_gdocs),('res_id','=',res_id)])
if not attach_ids:
google_template_id = config.gdocs_resource_id
attach_id = self.copy_gdoc(cr, uid, config.model_id, res_id, name_gdocs, google_template_id, context=context)
else:
attach_id = attach_ids[0]
attachments = self.browse(cr, uid, attach_id, context)
attachment['url'] = attachments.url
return attachment
class config(osv.osv):
_name = 'google.docs.config'
_description = "Google Drive templates config"
attach_pool = self.pool.get("ir.attachment")
attach_ids = attach_pool.search(cr, uid, [('res_model','=',res_model),('name','=',name_gdocs),('res_id','=',res_id)])
url = False
if attach_ids:
attachment = attach_pool.browse(cr, uid, attach_ids[0], context)
url = attachment.url
res[config.id] = {'name':name_gdocs, 'url': url}
return res
def _list_all_models(self, cr, uid, context=None):
cr.execute("SELECT model, name from ir_model order by name")
@ -207,20 +122,27 @@ class config(osv.osv):
key = url.query.split('=')[1]
else:
key = res[3]
res_id = resource + ":" + key
result[data.id] = str(res_id)
result[data.id] = str(key)
except:
raise osv.except_osv(_('Incorrect URL!'), _("Please enter a valid URL."))
return result
def _client_id_get(self, cr, uid, ids, name, arg, context=None):
result = {}
for config_id in ids:
user = self.pool.get('res.users').browse(cr, SUPERUSER_ID, uid)
result[config_id] = user.company_id.google_client_id
return result
_columns = {
'name' : fields.char('Template Name', required=True, size=1024),
'model_id': fields.selection(_list_all_models, 'Model', required=True),
'filter_id' : fields.many2one('ir.filters', 'Filter'),
'gdocs_template_url': fields.char('Template URL', required=True, size=1024),
'gdocs_resource_id' : fields.function(_resource_get,type="char" ,string='Resource Id',store=True),
'gdocs_resource_id' : fields.function(_resource_get,type="char" ,string='Resource Id'),
'google_client_id' : fields.function(_client_id_get,type="char" ,string='Google Client '),
'name_template': fields.char('Google Drive Name Pattern', size=64, help='Choose how the new google drive will be named, on google side. Eg. gdoc_%(field_name)s', required=True),
}
}
def onchange_model_id(self, cr, uid, ids, model_id, context=None):
res = {'domain':{'filter_id':[]}}
@ -244,3 +166,10 @@ class config(osv.osv):
]
config()
class res_company(osv.osv):
_inherit = "res.company"
_columns = {
'google_client_id': fields.char('Google Client ID', size=200),
}

View File

@ -82,6 +82,18 @@
</field>
</record>
<record model="ir.ui.view" id="view_company_inherit_form2">
<field name="name">res.company.form.inherit</field>
<field name="inherit_id" ref="base.view_company_form" />
<field name="model">res.company</field>
<field name="arch" type="xml">
<xpath expr="//group[@name='account_grp']" position="after">
<group string="Google Configuration">
<field name='google_client_id'/>
</group>
</xpath>
</field>
</record>
<menuitem name='Google Drive configuration' id='menu_gdocs_config' parent='base.menu_administration'/>
<menuitem id='menu_gdocs_model_config' parent='menu_gdocs_config' action='action_google_docs_users_config'/>
</data>

View File

@ -0,0 +1,7 @@
var gapi=window.gapi=window.gapi||{};gapi._bs=new Date().getTime();(function(){var f=null,g=encodeURIComponent,k=window,m=decodeURIComponent,n="push",r="test",t="shift",u="replace",y="length",B="split",C="join";var D=k,E=document,aa=D.location,ba=function(){},ca=/\[native code\]/,G=function(a,b,c){return a[b]=a[b]||c},da=function(a){for(var b=0;b<this[y];b++)if(this[b]===a)return b;return-1},ea=function(a){a=a.sort();for(var b=[],c=void 0,d=0;d<a[y];d++){var e=a[d];e!=c&&b[n](e);c=e}return b},H=function(){var a;if((a=Object.create)&&ca[r](a))a=a(f);else{a={};for(var b in a)a[b]=void 0}return a},I=G(D,"gapi",{});var J;J=G(D,"___jsl",H());G(J,"I",0);G(J,"hel",10);var K=function(){var a=aa.href,b;if(J.dpo)b=J.h;else{b=J.h;var c=RegExp("([#].*&|[#])jsh=([^&#]*)","g"),d=RegExp("([?#].*&|[?#])jsh=([^&#]*)","g");if(a=a&&(c.exec(a)||d.exec(a)))try{b=m(a[2])}catch(e){}}return b},fa=function(a){var b=G(J,"PQ",[]);J.PQ=[];var c=b[y];if(0===c)a();else for(var d=0,e=function(){++d===c&&a()},h=0;h<c;h++)b[h](e)},L=function(a){return G(G(J,"H",H()),a,H())};var M=G(J,"perf",H()),N=G(M,"g",H()),ga=G(M,"i",H());G(M,"r",[]);H();H();var O=function(a,b,c){var d=M.r;"function"===typeof d?d(a,b,c):d[n]([a,b,c])},Q=function(a,b,c){b&&0<b[y]&&(b=P(b),c&&0<c[y]&&(b+="___"+P(c)),28<b[y]&&(b=b.substr(0,28)+(b[y]-28)),c=b,b=G(ga,"_p",H()),G(b,c,H())[a]=(new Date).getTime(),O(a,"_p",c))},P=function(a){return a[C]("__")[u](/\./g,"_")[u](/\-/g,"_")[u](/\,/g,"_")};var S=H(),T=[],U=function(a){throw Error("Bad hint"+(a?": "+a:""));};T[n](["jsl",function(a){for(var b in a)if(Object.prototype.hasOwnProperty.call(a,b)){var c=a[b];"object"==typeof c?J[b]=G(J,b,[]).concat(c):G(J,b,c)}if(b=a.u)a=G(J,"us",[]),a[n](b),(b=/^https:(.*)$/.exec(b))&&a[n]("http:"+b[1])}]);var ha=/^(\/[a-zA-Z0-9_\-]+)+$/,ia=/^[a-zA-Z0-9\-_\.!]+$/,ja=/^gapi\.loaded_[0-9]+$/,ka=/^[a-zA-Z0-9,._-]+$/,oa=function(a,b,c,d){var e=a[B](";"),h=S[e[t]()],l=f;h&&(l=h(e,b,c,d));if(!(b=!l))b=l,c=b.match(la),d=b.match(ma),b=!(d&&1===d[y]&&na[r](b)&&c&&1===c[y]);b&&U(a);return l},qa=function(a,b,c,d){a=pa(a);ja[r](c)||U("invalid_callback");b=V(b);d=d&&d[y]?V(d):f;var e=function(a){return g(a)[u](/%2C/g,",")};return[g(a.d)[u](/%2C/g,",")[u](/%2F/g,"/"),"/k=",e(a.version),"/m=",e(b),d?"/exm="+e(d):
"","/rt=j/sv=1/d=1/ed=1",a.a?"/am="+e(a.a):"",a.b?"/rs="+e(a.b):"","/cb=",e(c)][C]("")},pa=function(a){"/"!==a.charAt(0)&&U("relative path");for(var b=a.substring(1)[B]("/"),c=[];b[y];){a=b[t]();if(!a[y]||0==a.indexOf("."))U("empty/relative directory");else if(0<a.indexOf("=")){b.unshift(a);break}c[n](a)}a={};for(var d=0,e=b[y];d<e;++d){var h=b[d][B]("="),l=m(h[0]),p=m(h[1]);2!=h[y]||(!l||!p)||(a[l]=a[l]||p)}b="/"+c[C]("/");ha[r](b)||U("invalid_prefix");c=W(a,"k",!0);d=W(a,"am");a=W(a,"rs");return{d:b,
version:c,a:d,b:a}},V=function(a){for(var b=[],c=0,d=a[y];c<d;++c){var e=a[c][u](/\./g,"_")[u](/-/g,"_");ka[r](e)&&b[n](e)}return b[C](",")},W=function(a,b,c){a=a[b];!a&&c&&U("missing: "+b);if(a){if(ia[r](a))return a;U("invalid: "+b)}return f},na=/^https?:\/\/[a-z0-9_.-]+\.google\.com(:\d+)?\/[a-zA-Z0-9_.,!=\-\/]+$/,ma=/\/cb=/g,la=/\/\//g,ra=function(){var a=K();if(!a)throw Error("Bad hint");return a};S.m=function(a,b,c,d){(a=a[0])||U("missing_hint");return"https://apis.google.com"+qa(a,b,c,d)};var X=decodeURI("%73cript"),Y=function(a,b){for(var c=[],d=0;d<a[y];++d){var e=a[d];e&&0>da.call(b,e)&&c[n](e)}return c},sa=function(a){"loading"!=E.readyState?Z(a):E.write("<"+X+' src="'+encodeURI(a)+'"></'+X+">")},Z=function(a){var b=E.createElement(X);b.setAttribute("src",a);b.async="true";(a=E.getElementsByTagName(X)[0])?a.parentNode.insertBefore(b,a):(E.head||E.body||E.documentElement).appendChild(b)},ta=function(a,b){var c=b&&b._c;if(c)for(var d=0;d<T[y];d++){var e=T[d][0],h=T[d][1];h&&Object.prototype.hasOwnProperty.call(c,
e)&&h(c[e],a,b)}},ua=function(a,b){$(function(){var c;c=b===K()?G(I,"_",H()):H();c=G(L(b),"_",c);a(c)})},wa=function(a,b){var c=b||{};"function"==typeof b&&(c={},c.callback=b);ta(a,c);var d=a?a[B](":"):[],e=c.h||ra(),h=G(J,"ah",H());if(!h["::"]||!d[y])va(d||[],c,e);else{for(var l=[],p=f;p=d[t]();){var v=p[B]("."),v=h[p]||h[v[1]&&"ns:"+v[0]||""]||e,s=l[y]&&l[l[y]-1]||f,z=s;if(!s||s.hint!=v)z={hint:v,c:[]},l[n](z);z.c[n](p)}var A=l[y];if(1<A){var F=c.callback;F&&(c.callback=function(){0==--A&&F()})}for(;d=
l[t]();)va(d.c,c,d.hint)}},va=function(a,b,c){a=ea(a)||[];var d=b.callback,e=b.config,h=b.timeout,l=b.ontimeout,p=f,v=!1;if(h&&!l||!h&&l)throw"Timeout requires both the timeout parameter and ontimeout parameter to be set";var s=G(L(c),"r",[]).sort(),z=G(L(c),"L",[]).sort(),A=[].concat(s),F=function(a,b){if(v)return 0;D.clearTimeout(p);z[n].apply(z,q);var d=((I||{}).config||{}).update;d?d(e):e&&G(J,"cu",[])[n](e);if(b){Q("me0",a,A);try{ua(b,c)}finally{Q("me1",a,A)}}return 1};0<h&&(p=D.setTimeout(function(){v=
!0;l()},h));var q=Y(a,z);if(q[y]){var q=Y(a,s),w=G(J,"CP",[]),x=w[y];w[x]=function(a){if(!a)return 0;Q("ml1",q,A);var b=function(b){w[x]=f;F(q,a)&&fa(function(){d&&d();b()})},c=function(){var a=w[x+1];a&&a()};0<x&&w[x-1]?w[x]=function(){b(c)}:b(c)};if(q[y]){var R="loaded_"+J.I++;I[R]=function(a){w[x](a);I[R]=f};a=oa(c,q,"gapi."+R,s);s[n].apply(s,q);Q("ml0",q,A);b.sync||D.___gapisync?sa(a):Z(a)}else w[x](ba)}else F(q)&&d&&d()};var $=function(a){if(J.hee&&0<J.hel)try{return a()}catch(b){J.hel--,wa("debug_error",function(){k.___jsl.hefn(b)})}else return a()};I.load=function(a,b){return $(function(){return wa(a,b)})};N.bs0=k.gapi._bs||(new Date).getTime();O("bs0");N.bs1=(new Date).getTime();O("bs1");delete k.gapi._bs;})();
gapi.load("client",{callback:window["gapi_onload"],_c:{"jsl":{"ci":{"services":{},"deviceType":"desktop","lexps":[102,103,100,71,98,96,110,108,79,106,45,17,86,81,112,61,30],"inline":{"css":1},"report":{},"oauth-flow":{"disableOpt":true,"authUrl":"https://accounts.google.com/o/oauth2/auth","proxyUrl":"https://accounts.google.com/o/oauth2/postmessageRelay","persist":true},"isLoggedIn":true,"isPlusUser":true,"iframes":{"additnow":{"methods":["launchurl"],"url":"https://apis.google.com/additnow/additnow.html?bsv"},"shortlists":{"url":"?bsv"},"plus":{"methods":["onauth"],"url":":socialhost:/u/:session_index:/_/pages/badge?bsv"},":socialhost:":"https://plusone.google.com","recobox":{"params":{"url":""},"url":":socialhost:/:session_prefix:_/widget/render/recobox?bsv"},"plus_followers":{"params":{"url":""},"url":":socialhost:/_/im/_/widget/render/plus/followers?bsv"},"autocomplete":{"params":{"url":""},"url":":socialhost:/:session_prefix:_/widget/render/autocomplete?bsv"},"plus_share":{"params":{"url":""},"url":":socialhost:/:session_prefix:_/+1/sharebutton?plusShare\u003dtrue\u0026bsv"},"savetowallet":{"url":"https://clients5.google.com/s2w/o/savetowallet?bsv"},"panoembed":{"url":"https://ssl.gstatic.com/pano/embed/?bsv"},"signin":{"methods":["onauth"],"params":{"url":""},"url":":socialhost:/:session_prefix:_/widget/render/signin?bsv"},"appcirclepicker":{"url":":socialhost:/:session_prefix:_/widget/render/appcirclepicker?bsv"},"commentcount":{"url":":socialhost:/:session_prefix:_/widget/render/commentcount?bsv"},"hangout":{"url":"https://talkgadget.google.com/:session_prefix:talkgadget/_/widget?bsv"},"plus_circle":{"params":{"url":""},"url":":socialhost:/:session_prefix:_/widget/plus/circle?bsv"},"savetodrive":{"methods":["save"],"url":"https://drive.google.com/savetodrivebutton?usegapi\u003d1\u0026bsv"},"card":{"url":":socialhost:/:session_prefix:_/hovercard/card?bsv"},"evwidget":{"params":{"url":""},"url":":socialhost:/:session_prefix:_/events/widget?bsv"},"zoomableimage":{"url":"https://ssl.gstatic.com/microscope/embed/?bsv"},":signuphost:":"https://plus.google.com","plusone":{"preloadUrl":["https://ssl.gstatic.com/s2/oz/images/stars/po/Publisher/sprite4-a67f741843ffc4220554c34bd01bb0bb.png"],"params":{"count":"","size":"","url":""},"url":":socialhost:/:session_prefix:_/+1/fastbutton?bsv"},"comments":{"methods":["scroll","openwindow"],"params":{"location":["search","hash"]},"url":":socialhost:/:session_prefix:_/widget/render/comments?bsv"}},"debug":{"host":"https://plusone.google.com","reportExceptionRate":0.05,"rethrowException":true},"csi":{"rate":0.01},"googleapis.config":{"mobilesignupurl":"https://m.google.com/app/plus/oob?"}},"h":"m;/_/scs/apps-static/_/js/k\u003doz.gapi.en.02N985CHyyc.O/m\u003d__features__/am\u003dIQ/rt\u003dj/d\u003d1/rs\u003dAItRSTPZZ0JVQCv9Qljsu0NQlsb1ZzD2zQ","u":"https://apis.google.com/js/client.js","hee":true,"fp":"e2aa6cd0095417dbec61deca3abed1394160dab3","dpo":false},"fp":"e2aa6cd0095417dbec61deca3abed1394160dab3","annotation":["autocomplete","profile","interactivepost"],"bimodal":["signin"]}});

View File

@ -1,71 +1,149 @@
openerp.google_docs = function(instance, m) {
var _t = instance.web._t,
QWeb = instance.web.qweb;
openerp.google_docs = function (instance, m) {
var _t = instance.web._t,
QWeb = instance.web.qweb;
instance.web.Sidebar.include({
start: function() {
start: function () {
var self = this;
var ids
var ids
this._super.apply(this, arguments);
var view = self.getParent();
var result;
if(view.fields_view.type == "form"){
ids = []
view.on("load_record", self, function(r){
ids = [r.id]
self.add_gdoc_items(view, r.id)
});
if (view.fields_view.type == "form") {
ids = []
view.on("load_record", self, function (r) {
ids = [r.id]
self.add_gdoc_items(view, r.id)
});
}
},
add_gdoc_items: function (view, res_id) {
var self = this;
var gdoc_item = _.indexOf(_.pluck(self.items.other, 'classname'), 'oe_share_gdoc');
if (gdoc_item !== -1) {
self.items.other.splice(gdoc_item, 1);
}
if (res_id) {
view.sidebar_eval_context().done(function (context) {
var ds = new instance.web.DataSet(this, 'ir.attachment', context);
ds.call('get_google_docs_config', [view.dataset.model, res_id, context]).done(function (r) {
if (!_.isEmpty(r)) {
_.each(r, function (res) {
var g_item = _.indexOf(_.pluck(self.items.other, 'label'), res.name);
if (g_item !== -1) {
self.items.other.splice(g_item, 1);
}
self.add_items('other', [{
label: res.name,
config_id: res.id,
res_id: res_id,
res_model: view.dataset.model,
callback: self.on_google_doc,
classname: 'oe_share_gdoc'
},
]);
})
}
});
});
}
},
fetch: function(model, fields, domain, ctx){
return new instance.web.Model(model).query(fields).filter(domain).context(ctx).all()
},
on_google_doc: function (doc_item) {
var self = this;
self.config = doc_item;
var loaded = self.fetch('google.docs.config',['gdocs_resource_id','google_client_id'],[['id','=',doc_item.config_id]])
.then(function(configs){
var ds = new instance.web.DataSet(self, 'google.docs.config');
ds.call('get_google_doc_name', [[doc_item.config_id], doc_item.res_id]).done(function (r) {
if (!_.isEmpty(r)) {
self.OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
self.VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=';
self.SCOPES = 'https://www.googleapis.com/auth/drive';
self.CLIENT_ID = configs[0].google_client_id;//'39623646228-4de6gmcai1n3mj14h08bcir2u42ln07e.apps.googleusercontent.com';
//self.GDOCS_TEMPLATE_URL = configs[0].gdocs_template_url;//'https://docs.google.com/document/d/1FOqv2iDaRcjdDz577dECgVvqhYN7bgAg3vB9M7DiCdM/edit';
self.gdoc_name = r[doc_item.config_id]['name'];
//var pattern = /(\/d\/)(.[^/]*)/;
self.GDOCS_TEMPLATE_ID = configs[0].gdocs_resource_id;//self.GDOCS_TEMPLATE_URL.match(pattern)[2];
self.gdoc_url = r[doc_item.config_id]['url'];
self.handleClientLoad();
}
});
});
},
handleClientLoad: function () {
var self = this;
window.setTimeout(function () {
self.checkAuth(self)
}, 1);
},
checkAuth: function (self) {
gapi.auth.authorize({
'client_id': self.CLIENT_ID,
'scope': self.SCOPES,
'immediate': true
}, function (authResult) {
self.handleAuthResult(self, authResult)
});
},
handleAuthResult: function (self, authResult) {
if (authResult && !authResult.error) {
self.clientLoad(self);
} else {
gapi.auth.authorize({
'client_id': self.CLIENT_ID,
'scope': self.SCOPES,
'immediate': false
},
self.handleAuthResult);
}
},
clientLoad: function (self) {
gapi.client.load('drive', 'v2', function () {
if (self.gdoc_url == false){
self.copyFile(self.config, self.GDOCS_TEMPLATE_ID, self.gdoc_name);
}
},
else{
window.open(self.gdoc_url, '_newtab');
}
});
},
add_gdoc_items: function(view, res_id){
var self = this;
var gdoc_item = _.indexOf(_.pluck(self.items.other,'classname'),'oe_share_gdoc');
if(gdoc_item !== -1)
{
self.items.other.splice(gdoc_item,1);
}
if( res_id ){
view.sidebar_eval_context().done(function (context) {
var ds = new instance.web.DataSet(this, 'ir.attachment', context);
ds.call('get_google_docs_config', [view.dataset.model, res_id, context]).done(function(r) {
if(!_.isEmpty(r)){
_.each(r,function(res){
var g_item = _.indexOf(_.pluck(self.items.other,'label'),res.name);
if(g_item !== -1)
{
self.items.other.splice(g_item,1);
}
self.add_items('other', [
{ label: res.name,
config_id: res.id,
callback: self.on_google_doc,
classname: 'oe_share_gdoc' },
]);
})
}
});
});
}
},
on_google_doc: function(doc_item) {
var self = this;
var view = self.getParent();
var ids = ( view.fields_view.type != "form" )? view.groups.get_selection().ids : [ view.datarecord.id ];
if( !_.isEmpty(ids) ){
view.sidebar_eval_context().done(function (context) {
var ds = new instance.web.DataSet(this, 'ir.attachment', context);
ds.call('get_google_attachment', [doc_item.config_id, view.datarecord.id, context]).done(function(res) {
window.open(res.url,"_blank");
view.reload();
})
});
}
}
copyFile: function (config, originFileId, copyTitle) {
var body = {
'title': copyTitle
};
var request = gapi.client.drive.files.copy({
'fileId': originFileId,
'resource': body
});
request.execute(function (resp) {
console.log('Copy ID: ' + resp.id);
var get_new_file = gapi.client.drive.files.get({
'fileId': resp.id
});
get_new_file.execute(function (file) {
var ds = new instance.web.DataSet(self, 'ir.attachment');
vals = {
'res_model': config.res_model,
'res_id': config.res_id,
'type': 'url',
'name': copyTitle,
'url': file.alternateLink
}
ds.call('create', [vals]).done(function (r) {
window.open(file.alternateLink, '_newtab');
});
});
});
},
});
};
};