def gsuite_callback(code=None): doc = frappe.get_doc("GSuite Settings") if code is None: return { 'url': 'https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id={}&scope={}&redirect_uri={}?cmd=frappe.integrations.doctype.gsuite_settings.gsuite_settings.gsuite_callback' .format(doc.client_id, SCOPES, get_request_site_address(True)) } else: try: data = { 'code': code, 'client_id': doc.client_id, 'client_secret': doc.get_password(fieldname='client_secret', raise_exception=False), 'redirect_uri': get_request_site_address(True) + '?cmd=frappe.integrations.doctype.gsuite_settings.gsuite_settings.gsuite_callback', 'grant_type': 'authorization_code' } r = requests.post('https://www.googleapis.com/oauth2/v4/token', data=data).json() frappe.db.set_value("Gsuite Settings", None, "authorization_code", code) if r.has_key('refresh_token'): frappe.db.set_value("Gsuite Settings", None, "refresh_token", r['refresh_token']) frappe.db.commit() return except Exception as e: frappe.throw(e.message)
def get_paytm_params(payment_details, order_id, paytm_config): # initialize a dictionary paytm_params = dict() redirect_uri = get_request_site_address( True ) + "/api/method/frappe.integrations.doctype.paytm_settings.paytm_settings.verify_transaction" paytm_params.update({ "MID": paytm_config.merchant_id, "WEBSITE": paytm_config.website, "INDUSTRY_TYPE_ID": paytm_config.industry_type_id, "CHANNEL_ID": "WEB", "ORDER_ID": order_id, "CUST_ID": payment_details['payer_email'], "EMAIL": payment_details['payer_email'], "TXN_AMOUNT": cstr(flt(payment_details['amount'], 2)), "CALLBACK_URL": redirect_uri, }) checksum = generateSignature(paytm_params, paytm_config.merchant_key) paytm_params.update({"CHECKSUMHASH": checksum}) return paytm_params
def get_context(context): """generate rss feed""" host = get_request_site_address() blog_list = frappe.db.sql("""\ select page_name as name, published_on, modified, title, content from `tabBlog Post` where ifnull(published,0)=1 order by published_on desc limit 20""", as_dict=1) for blog in blog_list: blog_page = cstr(urllib.quote(blog.name.encode("utf-8"))) + ".html" blog.link = urllib.basejoin(host, blog_page) blog.content = escape_html(blog.content or "") if blog_list: modified = max((blog['modified'] for blog in blog_list)) else: modified = now() blog_settings = frappe.get_doc('Blog Settings', 'Blog Settings') context = { 'title': blog_settings.blog_title or "Blog", 'description': blog_settings.blog_introduction or "", 'modified': modified, 'items': blog_list, 'link': host + '/blog' } # print context return context
def get_context(context): """generate the sitemap XML""" host = get_request_site_address() links = [] for route, page in iteritems(get_pages()): if not page.no_sitemap: links.append({ <<<<<<< HEAD "loc": urllib.basejoin(host, quote(page.name.encode("utf-8"))), ======= "loc": urljoin(host, quote(page.name.encode("utf-8"))), >>>>>>> 176d241496ede1357a309fa44a037b757a252581 "lastmod": nowdate() }) for route, data in iteritems(get_all_page_context_from_doctypes()): links.append({ <<<<<<< HEAD "loc": urllib.basejoin(host, quote((route or "").encode("utf-8"))), ======= "loc": urljoin(host, quote((route or "").encode("utf-8"))), >>>>>>> 176d241496ede1357a309fa44a037b757a252581 "lastmod": get_datetime(data.get("modified")).strftime("%Y-%m-%d") }) return {"links":links}
def token(code=None, state=None, account=None): CLIENT_ID = frappe.db.get_single_value('GSlides Config', 'client_id') CLIENT_SECRET = frappe.db.get_single_value('GSlides Config', 'client_secret') redirect_uri = get_request_site_address(True) + "?cmd=totall.slides.token" if code is None: # AG - 24 Sep 2020 - Se autentica para obtener code y redirecciona a redirect_uri para volver a correr token return { 'url': 'https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&prompt=consent&client_id={}&include_granted_scopes=true&scope={}&redirect_uri={}'.format(CLIENT_ID, SCOPES, redirect_uri) } else: try: data = {'code': code, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET , 'redirect_uri': redirect_uri, 'grant_type': 'authorization_code'} # AG - 24 Sep 2020 - envia los datos para obtener los claves token r = requests.post('https://www.googleapis.com/oauth2/v4/token', data=data).json() frappe.db.set_value("GSlides Config", "GSlides Config", "authorization_code", code) if 'access_token' in r: frappe.db.set_value("GSlides Config", "GSlides Config", "access_token", r['access_token']) if 'refresh_token' in r: frappe.db.set_value("GSlides Config", "GSlides Config", "refresh_token", r['refresh_token']) frappe.db.commit() frappe.local.response["type"] = "redirect" frappe.local.response["location"] = "exito.html" return except Exception as e: frappe.throw(e.message)
def get_dropbox_settings(redirect_uri=False): settings = frappe.get_doc("Dropbox Settings") app_details = { "app_key": settings.app_access_key or frappe.conf.dropbox_access_key, "app_secret": settings.get_password(fieldname="app_secret_key", raise_exception=False) if settings.app_secret_key else frappe.conf.dropbox_secret_key, 'access_token': settings.get_password('dropbox_access_token', raise_exception=False) if settings.dropbox_access_token else '', 'access_key': settings.get_password('dropbox_access_key', raise_exception=False), 'access_secret': settings.get_password('dropbox_access_secret', raise_exception=False) } if redirect_uri: app_details.update({ 'rediret_uri': get_request_site_address(True) \ + '/api/method/frappe.integrations.doctype.dropbox_settings.dropbox_settings.dropbox_auth_finish' \ if settings.app_secret_key else frappe.conf.dropbox_broker_site\ + '/api/method/dropbox_erpnext_broker.www.setup_dropbox.generate_dropbox_access_token', }) if not app_details['app_key'] or not app_details['app_secret']: raise Exception( _("Please set Dropbox access keys in your site config")) return app_details
def mautic_callback(code=None): doc = frappe.get_doc("Mautic Settings") if code is None: pass else: frappe.db.set_value("Mautic Settings", None, "authorization_code", code) try: data = { 'client_id': doc.client_id, 'client_secret': doc.get_password(fieldname='client_secret', raise_exception=False), 'redirect_uri': get_request_site_address(True) + '?cmd=mautic_integration.mautic_integration.doctype.mautic_settings.mautic_settings.mautic_callback', 'code': code, 'grant_type': 'authorization_code' } r = requests.post(doc.base_url + '/oauth/v2/token', data=data).json() if 'refresh_token' in r: frappe.db.set_value("Mautic Settings", None, "refresh_token", r['refresh_token']) if 'access_token' in r: frappe.db.set_value("Mautic Settings", None, "session_token", r['access_token']) frappe.db.commit() return except Exception as e: frappe.throw(e.message)
def google_callback(code=None, state=None, account=None): redirect_uri = get_request_site_address(True) + "?cmd=frappe.integrations.doctype.gcalendar_settings.gcalendar_settings.google_callback" if account is not None: frappe.cache().hset("gcalendar_account","GCalendar Account", account) doc = frappe.get_doc("GCalendar Settings") if code is None: return { 'url': 'https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&prompt=consent&client_id={}&include_granted_scopes=true&scope={}&redirect_uri={}'.format(doc.client_id, SCOPES, redirect_uri) } else: try: account = frappe.get_doc("GCalendar Account", frappe.cache().hget("gcalendar_account", "GCalendar Account")) data = {'code': code, 'client_id': doc.client_id, 'client_secret': doc.get_password(fieldname='client_secret',raise_exception=False), 'redirect_uri': redirect_uri, 'grant_type': 'authorization_code'} r = requests.post('https://www.googleapis.com/oauth2/v4/token', data=data).json() frappe.db.set_value("GCalendar Account", account.name, "authorization_code", code) if 'access_token' in r: frappe.db.set_value("GCalendar Account", account.name, "session_token", r['access_token']) if 'refresh_token' in r: frappe.db.set_value("GCalendar Account", account.name, "refresh_token", r['refresh_token']) frappe.db.commit() frappe.local.response["type"] = "redirect" frappe.local.response["location"] = "/integrations/gcalendar-success.html" return except Exception as e: frappe.throw(e.message)
def google_callback(code=None, state=None, account=None): redirect_uri = get_request_site_address(True) + "?cmd=gcalendar.gcalendar.doctype.gcalendar_settings.gcalendar_settings.google_callback" if account is not None: frappe.cache().hset("gcalendar_account","GCalendar Account", account) doc = frappe.get_doc("GCalendar Settings") if code is None: return { 'url': 'https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&prompt=consent&client_id={}&include_granted_scopes=true&scope={}&redirect_uri={}'.format(doc.client_id, SCOPES, redirect_uri) } else: try: account = frappe.get_doc("GCalendar Account", frappe.cache().hget("gcalendar_account", "GCalendar Account")) data = {'code': code, 'client_id': doc.client_id, 'client_secret': doc.get_password(fieldname='client_secret',raise_exception=False), 'redirect_uri': redirect_uri, 'grant_type': 'authorization_code'} r = requests.post('https://www.googleapis.com/oauth2/v4/token', data=data).json() frappe.db.set_value("GCalendar Account", account.name, "authorization_code", code) if 'access_token' in r: frappe.db.set_value("GCalendar Account", account.name, "session_token", r['access_token']) if 'refresh_token' in r: frappe.db.set_value("GCalendar Account", account.name, "refresh_token", r['refresh_token']) frappe.db.commit() return except Exception as e: frappe.throw(e.message)
def get_context(context): """generate the sitemap XML""" host = get_request_site_address() links = [] for page in get_pages(): if not page.no_sitemap: links.append({ "loc": urllib.basejoin(host, urllib.quote(page.name.encode("utf-8"))), "lastmod": "2014-01-01" }) def add_links(doctype, condition_field, order_by): meta = frappe.get_meta(doctype) page_name = "page_name" condition = "" if meta.get_field("parent_website_route"): page_name = """concat(ifnull(parent_website_route, ""), if(ifnull(parent_website_route, "")="", "", "/"), page_name)""" if condition_field: condition ="where ifnull({0}, 0)=1".format(condition_field) for route in frappe.db.sql("select {0}, modified from `tab{1}` {2}".format(page_name, doctype, condition)): if route[0]: links.append({ "loc": urllib.basejoin(host, urllib.quote(route[0].encode("utf-8"))), "lastmod": get_datetime(route[1]).strftime("%Y-%m-%d") }) process_generators(add_links) return {"links":links}
def get_context(context): """generate rss feed""" host = get_request_site_address() blog_list = frappe.db.sql("""\ select route as name, published_on, modified, title, content from `tabBlog Post` where ifnull(published,0)=1 order by published_on desc limit 20""", as_dict=1) for blog in blog_list: blog_page = cstr(urllib.quote(blog.route.encode("utf-8"))) blog.link = urllib.basejoin(host, blog_page) blog.content = escape_html(blog.content or "") if blog_list: modified = max((blog['modified'] for blog in blog_list)) else: modified = now() blog_settings = frappe.get_doc('Blog Settings', 'Blog Settings') context = { 'title': blog_settings.blog_title or "Blog", 'description': blog_settings.blog_introduction or "", 'modified': modified, 'items': blog_list, 'link': host + '/blog' } # print context return context
def authorize_access(g_contact, reauthorize=None): """ If no Authorization code get it from Google and then request for Refresh Token. Google Contact Name is set to flags to set_value after Authorization Code is obtained. """ google_settings = frappe.get_doc("Google Settings") google_contact = frappe.get_doc("Google Contacts", g_contact) redirect_uri = get_request_site_address(True) + "?cmd=frappe.integrations.doctype.google_contacts.google_contacts.google_callback" if not google_contact.authorization_code or reauthorize: frappe.cache().hset("google_contacts", "google_contact", google_contact.name) return get_authentication_url(client_id=google_settings.client_id, redirect_uri=redirect_uri) else: try: data = { "code": google_contact.authorization_code, "client_id": google_settings.client_id, "client_secret": google_settings.get_password(fieldname="client_secret", raise_exception=False), "redirect_uri": redirect_uri, "grant_type": "authorization_code" } r = requests.post(get_auth_url(), data=data).json() if "refresh_token" in r: frappe.db.set_value("Google Contacts", google_contact.name, "refresh_token", r.get("refresh_token")) frappe.db.commit() frappe.local.response["type"] = "redirect" frappe.local.response["location"] = "/app/Form/Google%20Contacts/{}".format(google_contact.name) frappe.msgprint(_("Google Contacts has been configured.")) except Exception as e: frappe.throw(e)
def get_context(context): """generate rss feed""" host = get_request_site_address() blog_list = frappe.db.sql( """\ select route as name, published_on, modified, title, content from `tabBlog Post` where ifnull(published,0)=1 order by published_on desc limit 20""", as_dict=1, ) for blog in blog_list: blog_page = cstr(quote(blog.name.encode("utf-8"))) blog.link = urljoin(host, blog_page) blog.content = escape_html(blog.content or "") if blog_list: modified = max((blog["modified"] for blog in blog_list)) else: modified = now() blog_settings = frappe.get_doc("Blog Settings", "Blog Settings") context = { "title": blog_settings.blog_title or "Blog", "description": blog_settings.blog_introduction or "", "modified": modified, "items": blog_list, "link": host + "/blog", } # print context return context
def get_account_balance(request_payload): """Call account balance API to send the request to the Mpesa Servers.""" try: mpesa_settings = frappe.get_doc( "Mpesa Settings", request_payload.get("reference_docname")) env = "production" if not mpesa_settings.sandbox else "sandbox" connector = MpesaConnector( env=env, app_key=mpesa_settings.consumer_key, app_secret=mpesa_settings.get_password("consumer_secret")) callback_url = get_request_site_address( True ) + "/api/method/erpnext.erpnext_integrations.doctype.mpesa_settings.mpesa_settings.process_balance_info" response = connector.get_balance(mpesa_settings.initiator_name, mpesa_settings.security_credential, mpesa_settings.till_number, 4, mpesa_settings.name, callback_url, callback_url) return response except Exception: frappe.log_error(title=_("Account Balance Processing Error")) frappe.throw(_("Please check your configuration and try again"), title=_("Error"))
def get_dropbox_settings(redirect_uri=False): if not frappe.conf.dropbox_broker_site: frappe.conf.dropbox_broker_site = 'https://dropbox.erpnext.com' settings = frappe.get_doc("Dropbox Settings") app_details = { "app_key": settings.app_access_key or frappe.conf.dropbox_access_key, "app_secret": settings.get_password(fieldname="app_secret_key", raise_exception=False) if settings.app_secret_key else frappe.conf.dropbox_secret_key, 'access_token': settings.get_password('dropbox_access_token', raise_exception=False) if settings.dropbox_access_token else '', 'access_key': settings.get_password('dropbox_access_key', raise_exception=False), 'access_secret': settings.get_password('dropbox_access_secret', raise_exception=False), 'file_backup':settings.file_backup } if redirect_uri: app_details.update({ 'redirect_uri': get_request_site_address(True) \ + '/api/method/frappe.integrations.doctype.dropbox_settings.dropbox_settings.dropbox_auth_finish' \ if settings.app_secret_key else frappe.conf.dropbox_broker_site\ + '/api/method/dropbox_erpnext_broker.www.setup_dropbox.generate_dropbox_access_token', }) if not app_details['app_key'] or not app_details['app_secret']: raise Exception(_("Please set Dropbox access keys in your site config")) return app_details
def google_callback(code=None, state=None, account=None): redirect_uri = get_request_site_address( True) + "?cmd=totall.gcal.google_callback" if code is None: return { 'url': 'https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&prompt=consent&client_id={}&include_granted_scopes=true&scope={}&redirect_uri={}' .format(CLIENT_ID, SCOPES, redirect_uri) } else: try: data = { 'code': code, 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'redirect_uri': redirect_uri, 'grant_type': 'authorization_code' } r = requests.post('https://www.googleapis.com/oauth2/v4/token', data=data).json() frappe.db.set_value("GCalendar Config", None, "authorization_code", code) if 'access_token' in r: frappe.db.set_value("GCalendar Config", None, "access_token", r['access_token']) if 'refresh_token' in r: frappe.db.set_value("GCalendar Config", None, "refresh_token", r['refresh_token']) frappe.db.commit() frappe.local.response["type"] = "redirect" frappe.local.response["location"] = "/integrations/gcal-exito.html" return except Exception as e: frappe.throw(e.message)
def generate_stk_push(**kwargs): """Generate stk push by making a API call to the stk push API.""" args = frappe._dict(kwargs) try: callback_url = get_request_site_address(True) + "/api/method/erpnext.erpnext_integrations.doctype.mpesa_settings.mpesa_settings.verify_transaction" mpesa_settings = frappe.get_doc("Mpesa Settings", args.payment_gateway[6:]) env = "production" if not mpesa_settings.sandbox else "sandbox" # for sandbox, business shortcode is same as till number business_shortcode = mpesa_settings.business_shortcode if env == "production" else mpesa_settings.till_number connector = MpesaConnector(env=env, app_key=mpesa_settings.consumer_key, app_secret=mpesa_settings.get_password("consumer_secret")) mobile_number = sanitize_mobile_number(args.sender) response = connector.stk_push( business_shortcode=business_shortcode, amount=args.request_amount, passcode=mpesa_settings.get_password("online_passkey"), callback_url=callback_url, reference_code=mpesa_settings.till_number, phone_number=mobile_number, description="POS Payment" ) return response except Exception: frappe.log_error(title=_("Mpesa Express Transaction Error")) frappe.throw(_("Issue detected with Mpesa configuration, check the error logs for more details"), title=_("Mpesa Express Error"))
def get_website_settings(): hooks = frappe.get_hooks() all_top_items = frappe.db.sql("""\ select * from `tabTop Bar Item` where parent='Website Settings' and parentfield='top_bar_items' order by idx asc""", as_dict=1) top_items = [d for d in all_top_items if not d['parent_label']] # attach child items to top bar for d in all_top_items: if d['parent_label']: for t in top_items: if t['label']==d['parent_label']: if not 'child_items' in t: t['child_items'] = [] t['child_items'].append(d) break context = frappe._dict({ 'top_bar_items': top_items, 'footer_items': frappe.db.sql("""\ select * from `tabTop Bar Item` where parent='Website Settings' and parentfield='footer_items' order by idx asc""", as_dict=1), "post_login": [ {"label": "Reset Password", "url": "update-password", "icon": "icon-key"}, {"label": "Logout", "url": "?cmd=web_logout", "icon": "icon-signout"} ] }) settings = frappe.get_doc("Website Settings", "Website Settings") for k in ["banner_html", "brand_html", "copyright", "twitter_share_via", "favicon", "facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup"]: if hasattr(settings, k): context[k] = settings.get(k) if not context.get("favicon"): context["favicon"] = "/assets/frappe/images/favicon.ico" if settings.address: context["footer_address"] = settings.address for k in ["facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup"]: context[k] = int(context.get(k) or 0) context.url = quote(str(get_request_site_address(full_address=True)), safe="/:") context.encoded_title = quote(encode(context.title or ""), str("")) for update_website_context in hooks.update_website_context or []: frappe.get_attr(update_website_context)(context) context.web_include_js = hooks.web_include_js or [] context.web_include_css = hooks.web_include_css or [] return context
def authorize_access(g_calendar, reauthorize=None): """ If no Authorization code get it from Google and then request for Refresh Token. Google Calendar Name is set to flags to set_value after Authorization Code is obtained. """ google_settings = frappe.get_doc("Google Settings") google_calendar = frappe.get_doc("Google Calendar", g_calendar) redirect_uri = get_request_site_address( True ) + "?cmd=frappe.integrations.doctype.google_calendar.google_calendar.google_callback" if not google_calendar.authorization_code or reauthorize: frappe.cache().hset("google_calendar", "google_calendar", google_calendar.name) return get_authentication_url(client_id=google_settings.client_id or frappe.conf.google_client_id, redirect_uri=redirect_uri) else: try: data = { "code": google_calendar.get_password(fieldname="authorization_code", raise_exception=False), "client_id": google_settings.client_id or frappe.conf.google_client_id, "client_secret": google_settings.get_password(fieldname="client_secret", raise_exception=False) or frappe.conf.google_client_secret, "redirect_uri": redirect_uri, "grant_type": "authorization_code" } r = requests.post(get_auth_url(), data=data).json() if "refresh_token" in r: frappe.db.set_value("Google Calendar", google_calendar.name, "refresh_token", r.get("refresh_token")) frappe.db.set_value("Google Calendar", google_calendar.name, "next_sync_token", None) frappe.db.commit() frappe.local.response["type"] = "redirect" frappe.local.response[ "location"] = "/desk#Form/{0}/{1}".format( quote("Google Calendar"), quote(google_calendar.name)) frappe.msgprint(_("Google Calendar has been configured.")) else: frappe.msgprint( _("Google Calendar configuration failed : {0}.").format( r.get("error_description") or str(r))) except Exception as e: frappe.throw(e)
def get_website_settings(context=None): hooks = frappe.get_hooks() context = context or frappe._dict() context = context.update({ 'top_bar_items': get_items('top_bar_items'), 'footer_items': get_items('footer_items'), "post_login": [ {"label": _("My Account"), "url": "/me"}, {"label": _("Logout"), "url": "/?cmd=web_logout"} ] }) settings = frappe.get_single("Website Settings") for k in ["banner_html", "banner_image", "brand_html", "copyright", "twitter_share_via", "facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup", "hide_footer_signup", "head_html", "title_prefix", "navbar_search", "enable_view_tracking", "footer_logo", "call_to_action", "call_to_action_url"]: if hasattr(settings, k): context[k] = settings.get(k) if settings.address: context["footer_address"] = settings.address for k in ["facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup"]: context[k] = int(context.get(k) or 0) if frappe.request: context.url = quote(str(get_request_site_address(full_address=True)), safe="/:") context.encoded_title = quote(encode(context.title or ""), str("")) for update_website_context in hooks.update_website_context or []: frappe.get_attr(update_website_context)(context) context.web_include_js = hooks.web_include_js or [] context.web_include_css = hooks.web_include_css or [] via_hooks = frappe.get_hooks("website_context") for key in via_hooks: context[key] = via_hooks[key] if key not in ("top_bar_items", "footer_items", "post_login") \ and isinstance(context[key], (list, tuple)): context[key] = context[key][-1] add_website_theme(context) if not context.get("favicon"): context["favicon"] = "/assets/frappe/images/favicon.png" if settings.favicon and settings.favicon != "attach_files:": context["favicon"] = settings.favicon context["hide_login"] = settings.hide_login return context
def get_website_settings(): hooks = frappe.get_hooks() context = frappe._dict({ 'top_bar_items': get_items('top_bar_items'), 'footer_items': get_items('footer_items'), "post_login": [ {"label": _("My Account"), "url": "/me"}, # {"class": "divider"}, {"label": _("Logout"), "url": "/?cmd=web_logout"} ] }) settings = frappe.get_single("Website Settings") for k in ["banner_html", "brand_html", "copyright", "twitter_share_via", "facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup", "hide_footer_signup", "head_html", "title_prefix", "navbar_search"]: if hasattr(settings, k): context[k] = settings.get(k) if settings.address: context["footer_address"] = settings.address for k in ["facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup"]: context[k] = int(context.get(k) or 0) if frappe.request: context.url = quote(str(get_request_site_address(full_address=True)), safe="/:") context.encoded_title = quote(encode(context.title or ""), str("")) for update_website_context in hooks.update_website_context or []: frappe.get_attr(update_website_context)(context) context.web_include_js = hooks.web_include_js or [] context.web_include_css = hooks.web_include_css or [] via_hooks = frappe.get_hooks("website_context") for key in via_hooks: context[key] = via_hooks[key] if key not in ("top_bar_items", "footer_items", "post_login") \ and isinstance(context[key], (list, tuple)): context[key] = context[key][-1] add_website_theme(context) if not context.get("favicon"): context["favicon"] = "/assets/frappe/images/favicon.png" if settings.favicon and settings.favicon != "attach_files:": context["favicon"] = settings.favicon return context
def get_context(context): """generate rss feed""" host = get_request_site_address() blog_list = frappe.db.sql("""\ select route as name, published_on, modified, title, content from `tabBlog Post` where ifnull(published,0)=1 order by published_on desc limit 20""", as_dict=1) for blog in blog_list: blog_page = cstr(quote(blog.name.encode("utf-8")))
def get_dropbox_authorize_url(): sess = get_dropbox_session() request_token = sess.obtain_request_token() return_address = get_request_site_address(True) \ + "?cmd=erpnext.setup.doctype.backup_manager.backup_dropbox.dropbox_callback" url = sess.build_authorize_url(request_token, return_address) return { "url": url, "key": request_token.key, "secret": request_token.secret, }
def get_dropbox_authorize_url(): sess = get_dropbox_session() request_token = sess.obtain_request_token() return_address = get_request_site_address(True) \ + "?cmd=frappe.integrations.doctype.dropbox_backup.dropbox_backup.dropbox_callback" url = sess.build_authorize_url(request_token, return_address) return { "url": url, "key": request_token.key, "secret": request_token.secret, }
def get_context(context): """generate the sitemap XML""" host = get_request_site_address() links = [] for l in frappe.db.sql("""select `tabWebsite Route`.page_name, `tabWebsite Route`.lastmod from `tabWebsite Route`, `tabWebsite Template` where `tabWebsite Route`.website_template = `tabWebsite Template`.name and ifnull(`tabWebsite Template`.no_sitemap, 0)=0""", as_dict=True): links.append({ "loc": urllib.basejoin(host, urllib.quote(l.page_name.encode("utf-8"))), "lastmod": l.lastmod }) return {"links":links}
def get_context(context): """generate the sitemap XML""" host = get_request_site_address() links = [] for route, page in iteritems(get_pages()): if page.sitemap: links.append({ "loc": urljoin(host, quote(page.name.encode("utf-8"))), "lastmod": nowdate() }) for route, data in iteritems(get_public_pages_from_doctypes()): links.append({ "loc": urljoin(host, quote((route or "").encode("utf-8"))), "lastmod": get_datetime(data.get("modified")).strftime("%Y-%m-%d") }) return {"links":links}
def get_context(context): """generate the sitemap XML""" host = get_request_site_address() links = [] for page in get_pages(): if not page.no_sitemap: links.append({ "loc": urllib.basejoin(host, urllib.quote(page.name.encode("utf-8"))), "lastmod": nowdate() }) for route, data in get_generator_routes().iteritems(): links.append({ "loc": urllib.basejoin(host, urllib.quote(route.encode("utf-8"))), "lastmod": get_datetime(data.get("modified")).strftime("%Y-%m-%d") }) return {"links":links}
def get_context(context): """generate the sitemap XML""" host = get_request_site_address() links = [] for l in frappe.db.sql("""select page_name, lastmod, controller from `tabWebsite Route`""", as_dict=True): module = frappe.get_module(l.controller) if l.controller else None if not getattr(module, "no_sitemap", False): links.append({ "loc": urllib.basejoin(host, urllib.quote(l.page_name.encode("utf-8"))), "lastmod": l.lastmod }) return {"links": links}
def get_context(context): """generate the sitemap XML""" host = get_request_site_address() links = [] for route, page in iteritems(get_pages()): if not page.no_sitemap: links.append({ "loc": urljoin(host, quote(page.name.encode("utf-8"))), "lastmod": nowdate() }) for route, data in iteritems(get_all_page_context_from_doctypes()): links.append({ "loc": urljoin(host, quote((route or "").encode("utf-8"))), "lastmod": get_datetime(data.get("modified")).strftime("%Y-%m-%d") }) return {"links":links}
def authorization_code(): doc = frappe.get_doc("Mautic Settings") data = { 'client_id': doc.client_id, 'client_secret': doc.get_password(fieldname='client_secret', raise_exception=False), 'redirect_uri': get_request_site_address(True) + '?cmd=mautic.mautic.doctype.mautic_settings.mautic_settings.mautic_callback', 'grant_type': 'authorization_code', 'response_type': 'code' } url = doc.base_url + '/oauth/v2/authorize?' + urlencode(data) return url
def authorize_access(reauthorize=None): """If no Authorization code get it from Google and then request for Refresh Token.""" google_settings = frappe.get_doc("Google Settings") website_settings = frappe.get_doc("Website Settings") redirect_uri = ( get_request_site_address(True) + "?cmd=frappe.website.doctype.website_settings.google_indexing.google_callback" ) if not website_settings.indexing_authorization_code or reauthorize: return get_authentication_url(client_id=google_settings.client_id, redirect_uri=redirect_uri) else: try: data = { "code": website_settings.indexing_authorization_code, "client_id": google_settings.client_id, "client_secret": google_settings.get_password(fieldname="client_secret", raise_exception=False), "redirect_uri": redirect_uri, "grant_type": "authorization_code", } res = requests.post(get_auth_url(), data=data).json() if "refresh_token" in res: frappe.db.set_value("Website Settings", website_settings.name, "indexing_refresh_token", res.get("refresh_token")) frappe.db.commit() frappe.local.response["type"] = "redirect" frappe.local.response["location"] = "/app/Form/{0}".format( quote("Website Settings")) frappe.msgprint(_("Google Indexing has been configured.")) except Exception as e: frappe.throw(e)
def validate(self): sandbox_url = "https://sandbox.safaricom.co.ke" live_url = "https://api.safaricom.co.ke" mpesa_settings = frappe.get_doc("Mpesa Settings", self.mpesa_settings) env = "production" if not mpesa_settings.sandbox else "sandbox" business_shortcode = (mpesa_settings.business_shortcode if env == "production" else mpesa_settings.till_number) if env == "sandbox": base_url = sandbox_url else: base_url = live_url token = get_token( app_key=mpesa_settings.consumer_key, app_secret=mpesa_settings.get_password("consumer_secret"), base_url=base_url, ) site_url = get_request_site_address(True) validation_url = ( site_url + "/api/method/posawesome.posawesome.api.m_pesa.validation") confirmation_url = ( site_url + "/api/method/posawesome.posawesome.api.m_pesa.confirmation") register_url = base_url + "/mpesa/c2b/v1/registerurl" payload = { "ShortCode": business_shortcode, "ResponseType": "Completed", "ConfirmationURL": validation_url, "ValidationURL": confirmation_url, } headers = { "Authorization": "Bearer {0}".format(token), "Content-Type": "application/json", } r = requests.post(register_url, headers=headers, json=payload) res = r.json() if res.get("ResponseDescription") == "Success": self.register_status = "Success" else: self.register_status = "Failed" frappe.msgprint(str(res))
def get_dropbox_authorize_url(): doc = frappe.get_doc("Dropbox Settings") sess = doc.get_dropbox_session() request_token = sess.obtain_request_token() doc.update({ "dropbox_access_key": request_token.key, "dropbox_access_secret": request_token.secret }) return_address = get_request_site_address(True) \ + "?cmd=frappe.integrations.doctype.dropbox_settings.dropbox_settings.dropbox_callback" url = sess.build_authorize_url(request_token, return_address) return { "url": url, "dropbox_access_key": request_token.key, "dropbox_access_secret": request_token.secret }
def get_context(context): """generate the sitemap XML""" host = get_request_site_address() links = [] robots = frappe.db.get_single_value("Website Settings", 'robots_txt').replace( 'Disallow: /', '').split('\n') for route, page in iteritems(get_pages()): flag = route not in robots if '/' in route: route_1 = route.split('/')[0] rb = [d.split('/')[0] for d in robots if '/*' in d] flag = route_1 not in rb if not page.no_sitemap and flag: links.append({ "loc": urljoin(host, quote(page.name.encode("utf-8"))), "lastmod": nowdate() }) for route, data in iteritems(get_all_page_context_from_doctypes()): flag = route not in robots if '/' in route: route_1 = route.split('/')[0] rb = [d.split('/')[0] for d in robots if '/*' in d] flag = route_1 not in rb if flag: links.append({ "loc": urljoin(host, quote((route or "").encode("utf-8"))), "lastmod": get_datetime(data.get("modified")).strftime("%Y-%m-%d") }) return {"links": links}
def gsuite_callback(code=None): doc = frappe.get_doc("GSuite Settings") if code is None: return { 'url': 'https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&response_type=code&client_id={}&scope={}&redirect_uri={}?cmd=frappe.integrations.doctype.gsuite_settings.gsuite_settings.gsuite_callback'.format(doc.client_id, SCOPES, get_request_site_address(True)) } else: try: data = {'code': code, 'client_id': doc.client_id, 'client_secret': doc.get_password(fieldname='client_secret',raise_exception=False), 'redirect_uri': get_request_site_address(True) + '?cmd=frappe.integrations.doctype.gsuite_settings.gsuite_settings.gsuite_callback', 'grant_type': 'authorization_code'} r = requests.post('https://www.googleapis.com/oauth2/v4/token', data=data).json() frappe.db.set_value("Gsuite Settings", None, "authorization_code", code) if 'refresh_token' in r: frappe.db.set_value("Gsuite Settings", None, "refresh_token", r['refresh_token']) frappe.db.commit() return except Exception as e: frappe.throw(e.message)
def get_context(context): """generate the sitemap XML""" host = get_request_site_address() links = [] for page in get_pages(): if not page.no_sitemap: links.append({ "loc": urllib.basejoin(host, urllib.quote(page.name.encode("utf-8"))), "lastmod": nowdate() }) for route, data in get_generator_routes().iteritems(): links.append({ "loc": urllib.basejoin(host, urllib.quote(route.encode("utf-8"))), "lastmod": get_datetime(data.get("modified")).strftime("%Y-%m-%d") }) return {"links": links}
def get_dropbox_authorize_url(): doc = frappe.get_doc("Dropbox Settings") sess = doc.get_dropbox_session() request_token = sess.obtain_request_token() doc.update({ "dropbox_access_key": request_token.key, "dropbox_access_secret": request_token.secret }) doc.save(ignore_permissions=False) return_address = get_request_site_address(True) \ + "?cmd=frappe.integrations.doctype.dropbox_settings.dropbox_settings.dropbox_callback" url = sess.build_authorize_url(request_token, return_address) return { "url": url, "dropbox_access_key": request_token.key, "dropbox_access_secret": request_token.secret }
def get_dropbox_settings(redirect_uri=False): if not frappe.conf.dropbox_broker_site: frappe.conf.dropbox_broker_site = "https://dropbox.erpnext.com" settings = frappe.get_doc("Dropbox Settings") app_details = { "app_key": settings.app_access_key or frappe.conf.dropbox_access_key, "app_secret": settings.get_password(fieldname="app_secret_key", raise_exception=False) if settings.app_secret_key else frappe.conf.dropbox_secret_key, "access_token": settings.get_password("dropbox_access_token", raise_exception=False) if settings.dropbox_access_token else "", "access_key": settings.get_password("dropbox_access_key", raise_exception=False), "access_secret": settings.get_password("dropbox_access_secret", raise_exception=False), "file_backup": settings.file_backup, "no_of_backups": settings.no_of_backups if settings.limit_no_of_backups else None, } if redirect_uri: app_details.update({ "redirect_uri": get_request_site_address(True) + "/api/method/frappe.integrations.doctype.dropbox_settings.dropbox_settings.dropbox_auth_finish" if settings.app_secret_key else frappe.conf.dropbox_broker_site + "/api/method/dropbox_erpnext_broker.www.setup_dropbox.generate_dropbox_access_token", }) if not app_details["app_key"] or not app_details["app_secret"]: raise Exception( _("Please set Dropbox access keys in your site config")) return app_details
def get_website_settings(): hooks = frappe.get_hooks() all_top_items = frappe.db.sql("""\ select * from `tabTop Bar Item` where parent='Website Settings' and parentfield='top_bar_items' order by idx asc""", as_dict=1) top_items = [d for d in all_top_items if not d['parent_label']] # attach child items to top bar for d in all_top_items: if d['parent_label']: for t in top_items: if t['label'] == d['parent_label']: if not 'child_items' in t: t['child_items'] = [] t['child_items'].append(d) break context = frappe._dict({ 'top_bar_items': top_items, 'footer_items': frappe.db.sql("""\ select * from `tabTop Bar Item` where parent='Website Settings' and parentfield='footer_items' order by idx asc""", as_dict=1), "post_login": [{ "label": "Reset Password", "url": "update-password", "icon": "icon-key" }, { "label": "Logout", "url": "?cmd=web_logout", "icon": "icon-signout" }] }) settings = frappe.get_doc("Website Settings", "Website Settings") for k in [ "banner_html", "brand_html", "copyright", "twitter_share_via", "favicon", "facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup", "no_sidebar" ]: if hasattr(settings, k): context[k] = settings.get(k) if not context.get("favicon"): context["favicon"] = "/assets/frappe/images/favicon.ico" if settings.address: context["footer_address"] = settings.address for k in [ "facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup" ]: context[k] = int(context.get(k) or 0) context.url = quote(str(get_request_site_address(full_address=True)), safe="/:") context.encoded_title = quote(encode(context.title or ""), str("")) for update_website_context in hooks.update_website_context or []: frappe.get_attr(update_website_context)(context) context.web_include_js = hooks.web_include_js or [] context.web_include_css = hooks.web_include_css or [] return context
def get_website_settings(): hooks = frappe.get_hooks() all_top_items = frappe.db.sql("""\ select * from `tabTop Bar Item` where parent='Website Settings' and parentfield='top_bar_items' order by idx asc""", as_dict=1) top_items = [d for d in all_top_items if not d['parent_label']] # attach child items to top bar for d in all_top_items: if d['parent_label']: for t in top_items: if t['label']==d['parent_label']: if not 'child_items' in t: t['child_items'] = [] t['child_items'].append(d) break context = frappe._dict({ 'top_bar_items': top_items, 'footer_items': frappe.db.sql("""\ select * from `tabTop Bar Item` where parent='Website Settings' and parentfield='footer_items' order by idx asc""", as_dict=1), "post_login": [ {"label": "My Account", "url": "/me"}, {"class": "divider"}, {"label": "Logout", "url": "/?cmd=web_logout"} ] }) settings = frappe.get_doc("Website Settings", "Website Settings") for k in ["banner_html", "brand_html", "copyright", "twitter_share_via", "facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup", "hide_footer_signup", "head_html"]: if hasattr(settings, k): context[k] = settings.get(k) if settings.address: context["footer_address"] = settings.address for k in ["facebook_share", "google_plus_one", "twitter_share", "linked_in_share", "disable_signup"]: context[k] = int(context.get(k) or 0) if frappe.request: context.url = quote(str(get_request_site_address(full_address=True)), safe="/:") context.encoded_title = quote(encode(context.title or ""), str("")) for update_website_context in hooks.update_website_context or []: frappe.get_attr(update_website_context)(context) context.web_include_js = hooks.web_include_js or [] context.web_include_css = hooks.web_include_css or [] via_hooks = frappe.get_hooks("website_context") for key in via_hooks: context[key] = via_hooks[key] if key not in ("top_bar_items", "footer_items", "post_login") \ and isinstance(context[key], (list, tuple)): context[key] = context[key][0] add_website_theme(context) if not context.get("favicon"): context["favicon"] = "/assets/frappe/images/favicon.png" if settings.favicon and settings.favicon != "attach_files:": context["favicon"] = settings.favicon return context