Exemplo n.º 1
0
 def is_temporary_system_problem(self, e):
     messages = (
         "-ERR [SYS/TEMP] Temporary system problem. Please try again later.",
         "Connection timed out",
     )
     for message in messages:
         if message in strip(cstr(e.message)) or message in strip(
                 cstr(getattr(e, 'strerror', ''))):
             return True
     return False
Exemplo n.º 2
0
	def __init__(self, sender='', recipients=(), subject='', alternative=0, reply_to=None, cc=(), bcc=(), email_account=None, expose_recipients=None):
		from email import charset as Charset
		Charset.add_charset('utf-8', Charset.QP, Charset.QP, 'utf-8')

		if isinstance(recipients, string_types):
			recipients = recipients.replace(';', ',').replace('\n', '')
			recipients = split_emails(recipients)

		# remove null
		recipients = filter(None, (strip(r) for r in recipients))

		self.sender = sender
		self.reply_to = reply_to or sender
		self.recipients = recipients
		self.subject = subject
		self.expose_recipients = expose_recipients

		self.msg_root = MIMEMultipart('mixed')
		self.msg_alternative = MIMEMultipart('alternative')
		self.msg_root.attach(self.msg_alternative)
		self.cc = cc or []
		self.bcc = bcc or []
		self.html_set = False

		self.email_account = email_account or get_outgoing_email_account(sender=sender)
Exemplo n.º 3
0
def get_web_image(file_url):
    # download
    file_url = dataent.utils.get_url(file_url)
    r = requests.get(file_url, stream=True)
    try:
        r.raise_for_status()
    except requests.exceptions.HTTPError as e:
        if "404" in e.args[0]:
            dataent.msgprint(_("File '{0}' not found").format(file_url))
        else:
            dataent.msgprint(
                _("Unable to read file format for {0}").format(file_url))
        raise

    image = Image.open(StringIO(r.content))

    try:
        filename, extn = file_url.rsplit("/", 1)[1].rsplit(".", 1)
    except ValueError:
        # the case when the file url doesn't have filename or extension
        # but is fetched due to a query string. example: https://encrypted-tbn3.gstatic.com/images?q=something
        filename = get_random_filename()
        extn = None

    extn = get_extension(filename, extn, r.content)
    filename = "/files/" + strip(unquote(filename))

    return image, filename, extn
Exemplo n.º 4
0
	def find_parent_based_on_subject_and_sender(self, communication, email):
		'''Find parent document based on subject and sender match'''
		parent = None

		if self.append_to and self.sender_field:
			if self.subject_field:
				# try and match by subject and sender
				# if sent by same sender with same subject,
				# append it to old coversation
				subject = dataent.as_unicode(strip(re.sub("(^\s*(fw|fwd|wg)[^:]*:|\s*(re|aw)[^:]*:\s*)*",
					"", email.subject, 0, flags=re.IGNORECASE)))

				parent = dataent.db.get_all(self.append_to, filters={
					self.sender_field: email.from_email,
					self.subject_field: ("like", "%{0}%".format(subject)),
					"creation": (">", (get_datetime() - relativedelta(days=10)).strftime(DATE_FORMAT))
				}, fields="name")

				# match only subject field
				# when the from_email is of a user in the system
				# and subject is atleast 10 chars long
				if not parent and len(subject) > 10 and is_system_user(email.from_email):
					parent = dataent.db.get_all(self.append_to, filters={
						self.subject_field: ("like", "%{0}%".format(subject)),
						"creation": (">", (get_datetime() - relativedelta(days=10)).strftime(DATE_FORMAT))
					}, fields="name")

			if parent:
				parent = dataent._dict(doctype=self.append_to, name=parent[0].name)
				return parent
Exemplo n.º 5
0
	def validate(self):
		"""validate the Email Addresses"""
		from dataent.utils import validate_email_add

		if not self.sender:
			self.sender = self.email_account.default_sender

		validate_email_add(strip(self.sender), True)
		self.reply_to = validate_email_add(strip(self.reply_to) or self.sender, True)

		self.replace_sender()
		self.replace_sender_name()

		self.recipients = [strip(r) for r in self.recipients]
		self.cc = [strip(r) for r in self.cc]
		self.bcc = [strip(r) for r in self.bcc]

		for e in self.recipients + (self.cc or []) + (self.bcc or []):
			validate_email_add(e, True)
Exemplo n.º 6
0
def get_context(context):
	context.javascript = dataent.db.get_single_value('Website Script',
		'javascript') or ""

	theme = get_active_theme()
	js = strip(theme and theme.js or "")
	if js:
		context.javascript += "\n" + js

	if not dataent.conf.developer_mode:
		context["google_analytics_id"] = (dataent.db.get_single_value("Website Settings", "google_analytics_id")
			or dataent.conf.get("google_analytics_id"))
Exemplo n.º 7
0
	def validate(self):
		if self.verified > 0:
			if dataent.db.get_value("User", dataent.session.user, "karma") < 100:
				dataent.throw(_("Only user with more than 100 karma can edit verified translations"))

			self.verified = 0

		source_msg = dataent.db.get_value("Source Message", self.source, "message")
		if get_placeholders_count(source_msg) != get_placeholders_count(self.translated):
			dataent.throw(_("Number of placehodlers (eg, {0}) do not match the source message"))

		# strip whitespace and whitespace like characters
		self.translated = strip(self.translated)
Exemplo n.º 8
0
def get_translation_dict_from_file(path, lang, app):
    """load translation dict from given path"""
    cleaned = {}
    if os.path.exists(path):
        csv_content = read_csv_file(path)

        for item in csv_content:
            if len(item) == 3:
                # with file and line numbers
                cleaned[item[1]] = strip(item[2])

            elif len(item) == 2:
                cleaned[item[0]] = strip(item[1])

            elif item:
                raise Exception(
                    "Bad translation in '{app}' for language '{lang}': {values}"
                    .format(app=app,
                            lang=lang,
                            values=repr(item).encode("utf-8")))

    return cleaned
Exemplo n.º 9
0
def parse_args(args):
	if not args:
		args = dataent.local.form_dict
	if isinstance(args, string_types):
		args = json.loads(args)

	args = dataent._dict(args)

	# strip the whitespace
	for key, value in args.items():
		if isinstance(value, string_types):
			args[key] = strip(value)

	return args
Exemplo n.º 10
0
    def autoname(self):
        if dataent.db.get_default("item_naming_by") == "Naming Series":
            if self.variant_of:
                if not self.item_code:
                    template_item_name = dataent.db.get_value(
                        "Item", self.variant_of, "item_name")
                    self.item_code = make_variant_item_code(
                        self.variant_of, template_item_name, self)
            else:
                from dataent.model.naming import set_name_by_naming_series
                set_name_by_naming_series(self)
                self.item_code = self.name

        self.item_code = strip(self.item_code)
        self.name = self.item_code
Exemplo n.º 11
0
	def make(self):
		"""build into msg_root"""
		headers = {
			"Subject":        strip(self.subject),
			"From":           self.sender,
			"To":             ', '.join(self.recipients) if self.expose_recipients=="header" else "<!--recipient-->",
			"Date":           email.utils.formatdate(),
			"Reply-To":       self.reply_to if self.reply_to else None,
			"CC":             ', '.join(self.cc) if self.cc and self.expose_recipients=="header" else None,
			'X-Dataent-Site':  get_url(),
		}

		# reset headers as values may be changed.
		for key, val in iteritems(headers):
			self.set_header(key, val)

		# call hook to enable apps to modify msg_root before sending
		for hook in dataent.get_hooks("make_email_body_message"):
			dataent.get_attr(hook)(self)
Exemplo n.º 12
0
def write_csv(app, lang, path):
	translations = get_translations_for_export(app, lang)

	parent = None
	parent_dict = {}
	if '-' in lang:
		# get translation from parent
		# for example es and es-GT
		parent = lang.split('-')[0]
		parent_dict = {}
		for t in get_translations_for_export(app, parent):
			parent_dict[t[1]] = t[2]

	with open(path, 'w') as msgfile:
		w = writer(msgfile, lineterminator='\n')
		for t in translations:
			# only write if translation is different from parent
			if (not parent) or (t[2] != parent_dict.get(t[1])):
				
				w.writerow([t[0] if t[0] else '', t[1], strip(t[2] or '')])
Exemplo n.º 13
0
 def has_login_limit_exceeded(self, e):
     return "-ERR Exceeded the login limit" in strip(cstr(e.message))