<commit_before># Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# License: MIT. See LICENSE

import email.utils
import functools
import imaplib
import socket
import time
from datetime import datetime, timedelta
from poplib import error_proto

import frappe
from frappe import _, are_emails_muted, safe_encode
from frappe.desk.form import assign_to
from frappe.email.receive import EmailServer, InboundMail, SentEmailInInboxError
from frappe.email.smtp import SMTPServer
from frappe.email.utils import get_port
from frappe.model.document import Document
from frappe.utils import cint, comma_or, cstr, parse_addr, validate_email_address
from frappe.utils.background_jobs import enqueue, get_jobs
from frappe.utils.error import raise_error_on_no_output
from frappe.utils.jinja import render_template
from frappe.utils.password import decrypt, encrypt
from frappe.utils.user import get_system_managers


class SentEmailInInbox(Exception):
	pass


def cache_email_account(cache_name):
	def decorator_cache_email_account(func):
		@functools.wraps(func)
		def wrapper_cache_email_account(*args, **kwargs):
			if not hasattr(frappe.local, cache_name):
				setattr(frappe.local, cache_name, {})

			cached_accounts = getattr(frappe.local, cache_name)
			match_by = list(kwargs.values()) + ["default"]
			matched_accounts = list(filter(None, [cached_accounts.get(key) for key in match_by]))
			if matched_accounts:
				return matched_accounts[0]

			matched_accounts = func(*args, **kwargs)
			cached_accounts.update(matched_accounts or {})
			return matched_accounts and list(matched_accounts.values())[0]

		return wrapper_cache_email_account

	return decorator_cache_email_account


class EmailAccount(Document):
	DOCTYPE = "Email Account"

	def autoname(self):
		"""Set name as `email_account_name` or make title from Email Address."""
		if not self.email_account_name:
			self.email_account_name = (
				self.email_id.split("@", 1)[0].replace("_", " ").replace(".", " ").replace("-", " ").title()
			)

		self.name = self.email_account_name

	def validate(self):
		"""Validate Email Address and check POP3/IMAP and SMTP connections is enabled."""

		if self.email_id:
			validate_email_address(self.email_id, True)

		if self.login_id_is_different:
			if not self.login_id:
				frappe.throw(_("Login Id is required"))
		else:
			self.login_id = None

		# validate the imap settings
		if self.enable_incoming and self.use_imap and len(self.imap_folder) <= 0:
			frappe.throw(_("You need to set one IMAP folder for {0}").format(frappe.bold(self.email_id)))

		if frappe.local.flags.in_patch or frappe.local.flags.in_test:
			return

		use_oauth = self.auth_method == "OAuth"

		if getattr(self, "service", "") != "GMail" and use_oauth:
			self.auth_method = "Basic"
			use_oauth = False

		if use_oauth:
			# no need for awaiting password for oauth
			self.awaiting_password = 0

		elif self.refresh_token:
			# clear access & refresh token
			self.refresh_token = self.access_token = None

		if not frappe.local.flags.in_install and not self.awaiting_password:
			if self.refresh_token or self.password or self.smtp_server in ("127.0.0.1", "localhost"):
				if self.enable_incoming:
					self.get_incoming_server()
					self.no_failed = 0<commit_msg>fix: clear password when saving account with Oauth<commit_after># Copyright (c) 2022, Frappe Technologies Pvt. Ltd. and contributors
# License: MIT. See LICENSE

import email.utils
import functools
import imaplib
import socket
import time
from datetime import datetime, timedelta
from poplib import error_proto

import frappe
from frappe import _, are_emails_muted, safe_encode
from frappe.desk.form import assign_to
from frappe.email.receive import EmailServer, InboundMail, SentEmailInInboxError
from frappe.email.smtp import SMTPServer
from frappe.email.utils import get_port
from frappe.model.document import Document
from frappe.utils import cint, comma_or, cstr, parse_addr, validate_email_address
from frappe.utils.background_jobs import enqueue, get_jobs
from frappe.utils.error import raise_error_on_no_output
from frappe.utils.jinja import render_template
from frappe.utils.password import decrypt, encrypt
from frappe.utils.user import get_system_managers


class SentEmailInInbox(Exception):
	pass


def cache_email_account(cache_name):
	def decorator_cache_email_account(func):
		@functools.wraps(func)
		def wrapper_cache_email_account(*args, **kwargs):
			if not hasattr(frappe.local, cache_name):
				setattr(frappe.local, cache_name, {})

			cached_accounts = getattr(frappe.local, cache_name)
			match_by = list(kwargs.values()) + ["default"]
			matched_accounts = list(filter(None, [cached_accounts.get(key) for key in match_by]))
			if matched_accounts:
				return matched_accounts[0]

			matched_accounts = func(*args, **kwargs)
			cached_accounts.update(matched_accounts or {})
			return matched_accounts and list(matched_accounts.values())[0]

		return wrapper_cache_email_account

	return decorator_cache_email_account


class EmailAccount(Document):
	DOCTYPE = "Email Account"

	def autoname(self):
		"""Set name as `email_account_name` or make title from Email Address."""
		if not self.email_account_name:
			self.email_account_name = (
				self.email_id.split("@", 1)[0].replace("_", " ").replace(".", " ").replace("-", " ").title()
			)

		self.name = self.email_account_name

	def validate(self):
		"""Validate Email Address and check POP3/IMAP and SMTP connections is enabled."""

		if self.email_id:
			validate_email_address(self.email_id, True)

		if self.login_id_is_different:
			if not self.login_id:
				frappe.throw(_("Login Id is required"))
		else:
			self.login_id = None

		# validate the imap settings
		if self.enable_incoming and self.use_imap and len(self.imap_folder) <= 0:
			frappe.throw(_("You need to set one IMAP folder for {0}").format(frappe.bold(self.email_id)))

		if frappe.local.flags.in_patch or frappe.local.flags.in_test:
			return

		use_oauth = self.auth_method == "OAuth"

		if getattr(self, "service", "") != "GMail" and use_oauth:
			self.auth_method = "Basic"
			use_oauth = False

		if use_oauth:
			# no need for awaiting password for oauth
			self.awaiting_password = 0
			self.password = <PASSWORD>

		elif self.refresh_token:
			# clear access & refresh token
			self.refresh_token = self.access_token = None

		if not frappe.local.flags.in_install and not self.awaiting_password:
			if self.refresh_token or self.password or self.smtp_server in ("127.0.0.1", "localhost"):
				if self.enable_incoming:
					self.get_incoming_server()
					self.no_failed = 0
{'fraction_non_alphanumeric': 0.09689158453373768, 'fraction_numerical': 0.005761940864291129, 'mean_word_length': 4.873552983081033, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5390186', 'n_tokens_mistral': 2374, 'n_tokens_neox': 2175, 'n_words': 556}