def send_email(*args, **kwargs): try: from kitchenrock_api.services.email import EmailService EmailService.sm_do_send(**args[0]) except Exception as e: print("Unable to sending email: " + str(e)) Utils.log_exception(e)
def save(self, data, return_http=True): try: if 'is_active' not in data: data['is_active'] = False serializer = self.user_serialiser_class(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) except Exception as e: Utils.log_exception(e) raise e
def async_job(cls, job_name, fname, args, delayed_time = 0): try: # Async class instance example from django_q.tasks import Async # instantiate an async task a = Async(fname, args, group=job_name) # you can set or change keywords afterwards a.cached = True # run it a.run() return True except Exception as e: Utils.log_exception(e) return None
def sm_do_send(cls, subject, to_add, context, template_name, reply_to=None): try: context['unsubscribe_link'] = False # unable to unsuncrible, example system email if context.get("email_token", None): context['unsubscribe_link'] = Utils.get_public_url(cls.__UNSUBSCRIBE_LINK + context.get("email_token")) context['public_base'] = Utils.get_public_url() context['privacy_link'] = Utils.get_public_url(cls.__PRIVACY_LINK) context['support_link'] = Utils.get_public_url(cls.__SUPPORT_LINK) # bcc = context.get("bcc", []) if to_add[0] == settings.BCC_EMAIL_ADDRESS: pass else: if settings.ALLOWED_EMAILS != "*": if settings.ALLOWED_EMAILS: to_add = [settings.ALLOWED_EMAILS] else: Utils.log("settings.ALLOWED_EMAILS is empty") return mail = TemplateEmail( subject=subject, template=template_name, context=context, from_email=u"{} Support <{}>".format(cls.__BRAND_NAME, settings.SUPPORT_EMAIL), to=to_add, # bcc=bcc, headers={"Reply-To": reply_to or cls.__REPLY_TO}, ) mail.send() except Exception as e: cls.log_exception(e)
def save(cls, user_data, **kwargs): with transaction.atomic(): add_new = True # profile_data = user_data.pop('profile') password = user_data.pop('password', None) user_email = user_data.get('email', None) if user_data.get("id"): user = cls.get_user(user_data['id']) else: user = None if user is not None: add_new = False # profile = user.profile else: user = User() current_email = user.email # All data must be validated at serializer tier for key in user_data: setattr(user, key, user_data[key]) # Set first password if add_new: if not password and not user.password: password = Utils.id_generator(8) user.set_password(password) user.save() if not user.email: user.email = "{0}@{1}".format(str(user.id), "kitchenrock.vn") user.save() # if add_new: # profile = UserProfile() # profile.user_id = user.id # for key in profile_data: # setattr(profile, key, profile_data[key]) # profile.save() send_verify_email = True if user.is_active: send_verify_email = False if user_email != current_email: cls.add_email(user.id, user.email, current_email=current_email, is_primary=True, password=password, send_verify_email=send_verify_email) if not add_new: # Reset cache cache_service = cls._get_cache_service() cache_service.delete(user.id) return cls.get_user(user.id)
def verify_email(cls, token, email_add, *args, **kwargs): """ Verify email address and active account """ template_name = kwargs.pop('template', 'verify') template_name = get_template(template_name) uid = kwargs.pop('uid', 'activation') subject = "Welcome to {}".format(cls.__BRAND_NAME) user_email = email_add verify_link = "" verify_link = Utils.get_public_url('/verify/{}/{}'.format(uid, token)) context = { 'verify_link': verify_link, 'email': email_add, 'password': kwargs.pop('password', None) } cls._sm_send_email(subject, [user_email], context, template_name, False, False)
def reset_link(cls, token, uid, *args, **kwargs): """ Send reset password link """ user = kwargs.get('user', None) user_id = kwargs.get('user_id', None) if not user and not user_id: raise EmailError('Please provide user or user id param.') if not user: user = UserService.get_user(user_id) template_name = get_template('reset-password') subject = 'Somebody requested a new password for your {} account'.format(cls.__BRAND_NAME) user_email = '"%s" <%s>' % (user.get_full_name(), user.email) link = Utils.get_public_url('/password/reset/{}/{}'.format(uid.decode('utf-8'), token)) context = { 'reset_link': link, 'username': user.email } cls._sm_send_email(subject, [user_email], context, template_name, False, False)
def gen_token(cls, user_id): text = str(user_id) + Utils.id_generator(10) + str(int(time.time())) hash_object = hashlib.md5(text.encode('utf-8')) return hash_object.hexdigest()
def download(cls, media_id, file_url): result = { "file_size": 0, "file_size_dl": 0, "file_name": False, "out_path": False, "success": 0, "error": "" } try: req = urllib.request.Request(file_url, headers={'User-Agent' : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36"}) u = urllib.request.urlopen(req) meta = u.info() mime_type = meta.getheaders("Content-Type")[0] file_size = int(meta.getheaders("Content-Length")[0]) disposition = False file_name = False if meta.getheaders("Content-Disposition"): disposition = meta.getheaders("Content-Disposition")[0] file_name = re.findall("filename=(\S+)", disposition)[0] file_name = Utils.normalize_str(file_name) file_name = re.sub(r'^"|"$', '', file_name) file_name = file_name.replace("_", "-") if not file_name: extends = { "video/3gpp": ".3gp", "video/mp4": ".mp4", 'image/jpeg': ".jpg", 'image/png': ".png" } file_name = "media-{0}{1}".format(media_id, extends[mime_type]) else: file_name = "media-{0}-{1}".format(media_id, file_name) base_path = settings.MEDIA_ROOT out_path = "{0}{1}".format(base_path, file_name) result["file_size"] = file_size result["mime_type"] = mime_type result["file_name"] = file_name result["out_path"] = out_path try: os.remove(out_path) except: pass f = open(out_path, 'wb') file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) f.close() success = (file_size_dl == file_size) result["file_size_dl"] = file_size_dl result["success"] = success except Exception as e: cls.log_exception(e) result['error'] = str(e) return result
def _gen_key(cls, length=KEY_SIZE): key = Utils.id_generator(length) while AppKey.objects.filter(key=key).exists(): key = Utils.id_generator(length) return key.upper()
def set_per_page(self, per_page): self._per_page = max(Utils.safe_int(per_page, 1), 1) return self
def set_offset(self, offset): self._offset = max(Utils.safe_int(offset, 0), -1) return self
def _log_debug(self, v): if self._debug: Utils.dump(v)
def _gen_unique_str(cls, length=DEFAULT_TOKEN_LENGTH): str = Utils.id_generator(length) if length < 40: while Api.objects.filter(token=str).exists(): str = Utils.id_generator(length) return str
def gen_loc_slug(loc, arg=None): return Utils.gen_search_slug('', loc.display_text)