def do_action(self): now = datetime.datetime.now() try: cmd_last_check = CommandsLastCheck.objects.get( command_type=self.label) logger.debug('Last check time is %s' % cmd_last_check.last_check) unseen_notices = UserNotification.objects.get_all_notifications( seen=False, time_since=cmd_last_check.last_check) logger.debug('Update last check time to %s' % now) cmd_last_check.last_check = now cmd_last_check.save() except CommandsLastCheck.DoesNotExist: logger.debug('No last check time found, get all unread notices.') unseen_notices = UserNotification.objects.get_all_notifications( seen=False) logger.debug('Create new last check time: %s' % now) CommandsLastCheck(command_type=self.label, last_check=now).save() email_ctx = {} for notice in unseen_notices: if email_ctx.has_key(notice.to_user): email_ctx[notice.to_user] += 1 else: email_ctx[notice.to_user] = 1 for to_user, count in email_ctx.items(): subject = subjects[1] if count > 1 else subjects[0] template = string.Template(email_templates[1]) if count > 1 else \ string.Template(email_templates[0]) content = template.substitute(to_user=to_user, count=count, site_name=site_name, url=url) try: send_mail(subject, content, settings.DEFAULT_FROM_EMAIL, [to_user], fail_silently=False) logger.info('Successfully sent email to %s' % to_user) except Exception, e: logger.error('Failed to send email to %s, error detail: %s' % (to_user, e))
def do_action(self): now = datetime.datetime.now() try: cmd_last_check = CommandsLastCheck.objects.get( command_type=self.label) logger.debug('Last check time is %s' % cmd_last_check.last_check) unseen_notices = UserNotification.objects.get_all_notifications( seen=False, time_since=cmd_last_check.last_check) logger.debug('Update last check time to %s' % now) cmd_last_check.last_check = now cmd_last_check.save() except CommandsLastCheck.DoesNotExist: logger.debug('No last check time found, get all unread notices.') unseen_notices = UserNotification.objects.get_all_notifications( seen=False) logger.debug('Create new last check time: %s' % now) CommandsLastCheck(command_type=self.label, last_check=now).save() email_ctx = {} for notice in unseen_notices: if email_ctx.has_key(notice.to_user): email_ctx[notice.to_user] += 1 else: email_ctx[notice.to_user] = 1 for to_user, count in email_ctx.items(): subject = subjects[1] if count > 1 else subjects[0] c = { 'to_user': to_user, 'notice_count': count, } try: send_html_email(subject, 'notifications/notice_email.html', c, settings.DEFAULT_FROM_EMAIL, [to_user]) logger.info('Successfully sent email to %s' % to_user) except Exception, e: logger.error('Failed to send email to %s, error detail: %s' % (to_user, e))
def do_action(self): now = datetime.datetime.now() try: cmd_last_check = CommandsLastCheck.objects.get( command_type=self.label) logger.debug('Last check time is %s' % cmd_last_check.last_check) unseen_notices = UserNotification.objects.get_all_notifications( seen=False, time_since=cmd_last_check.last_check) logger.debug('Update last check time to %s' % now) cmd_last_check.last_check = now cmd_last_check.save() except CommandsLastCheck.DoesNotExist: logger.debug('No last check time found, get all unread notices.') unseen_notices = UserNotification.objects.get_all_notifications( seen=False) logger.debug('Create new last check time: %s' % now) CommandsLastCheck(command_type=self.label, last_check=now).save() email_ctx = {} for notice in unseen_notices: if notice.to_user in email_ctx: email_ctx[notice.to_user] += 1 else: email_ctx[notice.to_user] = 1 for to_user, count in email_ctx.items(): # save current language cur_language = translation.get_language() # get and active user language user_language = self.get_user_language(to_user) translation.activate(user_language) logger.debug('Set language code to %s for user: %s' % (user_language, to_user)) self.stdout.write('[%s] Set language code to %s' % (str(datetime.datetime.now()), user_language)) notices = [] for notice in unseen_notices: logger.info('Processing unseen notice: [%s]' % (notice)) d = json.loads(notice.detail) repo_id = d.get('repo_id', None) group_id = d.get('group_id', None) try: if repo_id and not seafile_api.get_repo(repo_id): notice.delete() continue if group_id and not ccnet_api.get_group(group_id): notice.delete() continue except Exception as e: logger.error(e) continue if notice.to_user != to_user: continue elif notice.is_user_message(): notice = self.format_user_message(notice) elif notice.is_group_msg(): notice = self.format_group_message(notice) elif notice.is_repo_share_msg(): notice = self.format_repo_share_msg(notice) elif notice.is_repo_share_to_group_msg(): notice = self.format_repo_share_to_group_msg(notice) elif notice.is_file_uploaded_msg(): notice = self.format_file_uploaded_msg(notice) elif notice.is_group_join_request(): notice = self.format_group_join_request(notice) elif notice.is_add_user_to_group(): notice = self.format_add_user_to_group(notice) elif notice.is_file_comment_msg(): notice = self.format_file_comment_msg(notice) notices.append(notice) if not notices: continue contact_email = Profile.objects.get_contact_email_by_user(to_user) to_user = contact_email # use contact email if any c = { 'to_user': to_user, 'notice_count': count, 'notices': notices, } try: send_html_email( _('New notice on %s') % settings.SITE_NAME, 'notifications/notice_email.html', c, None, [to_user]) logger.info('Successfully sent email to %s' % to_user) self.stdout.write('[%s] Successfully sent email to %s' % (str(datetime.datetime.now()), to_user)) except Exception as e: logger.error('Failed to send email to %s, error detail: %s' % (to_user, e)) self.stderr.write( '[%s] Failed to send email to %s, error detail: %s' % (str(datetime.datetime.now()), to_user, e)) # restore current language translation.activate(cur_language)
def do_action(self): now = datetime.now() today = datetime.now().replace(hour=0).replace(minute=0).replace( second=0).replace(microsecond=0) # 1. get all users who are connected wechat work socials = UserSocialAuth.objects.filter(provider='weixin-work') users = [(x.username, x.uid) for x in socials] if not users: return user_uid_map = {} for username, uid in users: user_uid_map[username] = uid # 2. get previous time that command last runs try: cmd_last_check = CommandsLastCheck.objects.get(command_type=self.label) self.log_debug('Last check time is %s' % cmd_last_check.last_check) last_check_dt = cmd_last_check.last_check cmd_last_check.last_check = now cmd_last_check.save() except CommandsLastCheck.DoesNotExist: last_check_dt = today self.log_debug('Create new last check time: %s' % now) CommandsLastCheck(command_type=self.label, last_check=now).save() # 3. get all unseen notices for those users qs = UserNotification.objects.filter( timestamp__gt=last_check_dt ).filter(seen=False).filter( to_user__in=user_uid_map.keys() ) user_notices = {} for q in qs: if q.to_user not in user_notices: user_notices[q.to_user] = [q] else: user_notices[q.to_user].append(q) # 4. send msg to users url = get_site_scheme_and_netloc().rstrip('/') + reverse('user_notification_list') for username, uid in users: notices = user_notices.get(username, []) count = len(notices) if count == 0: continue # save current language cur_language = translation.get_language() # get and active user language user_language = self.get_user_language(username) translation.activate(user_language) self.log_debug('Set language code to %s for user: %s' % ( user_language, username)) title = ungettext( "\n" "You've got 1 new notice on %(site_name)s:\n", "\n" "You've got %(num)s new notices on %(site_name)s:\n", count ) % { 'num': count, 'site_name': get_site_name(), } content = ''.join([wrap_div(x.format_msg()) for x in notices]) self.send_wx_msg(uid, title, content, url) translation.activate(cur_language)
def do_action(self): # check before start if not work_weixin_notifications_check(): self.log_error('work weixin notifications settings check failed') return access_token = get_work_weixin_access_token() if not access_token: self.log_error('can not get access_token') return notice_url = WORK_WEIXIN_NOTIFICATIONS_URL + '?access_token=' + access_token detail_url = DTABLE_WEB_SERVICE_URL # start now = datetime.utcnow() today = datetime.utcnow().replace(hour=0).replace(minute=0). \ replace(second=0).replace(microsecond=0) # 1. get all users who are connected work weixin socials = SocialAuthUser.objects.filter( provider=WORK_WEIXIN_PROVIDER, uid__contains=WORK_WEIXIN_UID_PREFIX) users = [(x.username, x.uid[len(WORK_WEIXIN_UID_PREFIX):]) for x in socials] self.log_info('Found %d users' % len(users)) if not users: return user_uid_map = dict() for username, uid in users: user_uid_map[username] = uid # 2. get previous time that command last runs try: cmd_last_check = CommandsLastCheck.objects.get( command_type=self.label) self.log_debug('Last check time is %s' % cmd_last_check.last_check) last_check_dt = cmd_last_check.last_check cmd_last_check.last_check = now cmd_last_check.save() except CommandsLastCheck.DoesNotExist: last_check_dt = today self.log_debug('Create new last check time: %s' % now) CommandsLastCheck(command_type=self.label, last_check=now).save() # 3. get all unseen row comments for those users user_list = list(user_uid_map.keys()) with connection.cursor() as cursor: cursor.execute( "SELECT * FROM dtable_notifications WHERE created_at > %s" "AND seen = FALSE AND username IN %s", [last_check_dt, user_list]) rows = cursor.fetchall() if len(rows) == 0: return user_notices = {} for row in rows: if row[1] not in user_notices: user_notices[row[1]] = [row] else: user_notices[row[1]].append(row) cur_language = translation.get_language() translation.activate('zh-cn') # set language to zh-cn self.log_info('Set language to zh-cn') # 4. send msg to users site_name = get_site_name() for username, uid in users: notices = user_notices.get(username, []) count = len(notices) if count == 0: continue title = ungettext( "\n" "You've got 1 new notice on %(site_name)s:\n", "\n" "You've got %(num)s new notices on %(site_name)s:\n", count) % { 'num': count, 'site_name': site_name, } content = '\n'.join([format_notice(x) for x in notices]) self.send_work_weixin_msg(uid, title, content, detail_url, notice_url) translation.activate(cur_language) # reset language self.log_info('Reset language success')
def do_action(self): now = datetime.datetime.now() try: cmd_last_check = CommandsLastCheck.objects.get(command_type=self.label) logger.debug('Last check time is %s' % cmd_last_check.last_check) unseen_notices = UserNotification.objects.get_all_notifications( seen=False, time_since=cmd_last_check.last_check) logger.debug('Update last check time to %s' % now) cmd_last_check.last_check = now cmd_last_check.save() except CommandsLastCheck.DoesNotExist: logger.debug('No last check time found, get all unread notices.') unseen_notices = UserNotification.objects.get_all_notifications( seen=False) logger.debug('Create new last check time: %s' % now) CommandsLastCheck(command_type=self.label, last_check=now).save() email_ctx = {} for notice in unseen_notices: if notice.to_user in email_ctx: email_ctx[notice.to_user] += 1 else: email_ctx[notice.to_user] = 1 for to_user, count in email_ctx.items(): # save current language cur_language = translation.get_language() # get and active user language user_language = self.get_user_language(to_user) translation.activate(user_language) logger.info('Set language code to %s', user_language) notices = [] for notice in unseen_notices: if notice.to_user != to_user: continue if notice.is_priv_file_share_msg(): notice = self.format_priv_file_share_msg(notice) elif notice.is_user_message(): notice = self.format_user_message(notice) elif notice.is_group_msg(): notice = self.format_group_message(notice) elif notice.is_grpmsg_reply(): notice = self.format_grpmsg_reply(notice) elif notice.is_repo_share_msg(): notice = self.format_repo_share_msg(notice) elif notice.is_file_uploaded_msg(): notice = self.format_file_uploaded_msg(notice) elif notice.is_group_join_request(): notice = self.format_group_join_request(notice) notices.append(notice) if not notices: continue c = { 'to_user': to_user, 'notice_count': count, 'notices': notices, } try: send_html_email(_('New notice on %s') % settings.SITE_NAME, 'notifications/notice_email.html', c, None, [to_user]) logger.info('Successfully sent email to %s' % to_user) except Exception as e: logger.error('Failed to send email to %s, error detail: %s' % (to_user, e)) # restore current language translation.activate(cur_language)
def do_action(self): # check before start if not work_weixin_notifications_check(): self.log_error('work weixin notifications settings check failed') return access_token = get_work_weixin_access_token() if not access_token: self.log_error('can not get access_token') self.work_weixin_notifications_url = WORK_WEIXIN_NOTIFICATIONS_URL + '?access_token=' + access_token self.detail_url = get_site_scheme_and_netloc().rstrip('/') + reverse( 'user_notification_list') site_name = get_site_name() # start now = datetime.now() today = datetime.now().replace(hour=0).replace(minute=0).replace( second=0).replace(microsecond=0) # 1. get all users who are connected work weixin socials = SocialAuthUser.objects.filter( provider=WORK_WEIXIN_PROVIDER, uid__contains=WORK_WEIXIN_UID_PREFIX) users = [(x.username, x.uid[len(WORK_WEIXIN_UID_PREFIX):]) for x in socials] self.log_info('Found %d users' % len(users)) if not users: return user_uid_map = {} for username, uid in users: user_uid_map[username] = uid # 2. get previous time that command last runs try: cmd_last_check = CommandsLastCheck.objects.get( command_type=self.label) self.log_debug('Last check time is %s' % cmd_last_check.last_check) last_check_dt = cmd_last_check.last_check cmd_last_check.last_check = now cmd_last_check.save() except CommandsLastCheck.DoesNotExist: last_check_dt = today self.log_debug('Create new last check time: %s' % now) CommandsLastCheck(command_type=self.label, last_check=now).save() # 3. get all unseen notices for those users qs = UserNotification.objects.filter( timestamp__gt=last_check_dt).filter(seen=False).filter( to_user__in=list(user_uid_map.keys())) self.log_info('Found %d notices' % qs.count()) if qs.count() == 0: return user_notices = {} for q in qs: if q.to_user not in user_notices: user_notices[q.to_user] = [q] else: user_notices[q.to_user].append(q) # save current language cur_language = translation.get_language() # active zh-cn translation.activate('zh-cn') self.log_info('the language is set to zh-cn') # 4. send msg to users for username, uid in users: notices = user_notices.get(username, []) count = len(notices) if count == 0: continue title = ungettext( "\n" "You've got 1 new notice on %(site_name)s:\n", "\n" "You've got %(num)s new notices on %(site_name)s:\n", count) % { 'num': count, 'site_name': site_name, } content = ''.join([wrap_div(x.format_msg()) for x in notices]) self.send_work_weixin_msg(uid, title, content) # reset language translation.activate(cur_language) self.log_info('reset language success')
def do_action(self): # check before start access_token = dingtalk_get_access_token() if not access_token: self.log_error('can not get access_token') self.dingtalk_message_send_to_conversation_url = DINGTALK_MESSAGE_SEND_TO_CONVERSATION_URL + '?access_token=' + access_token self.detail_url = get_site_scheme_and_netloc().rstrip('/') + reverse( 'user_notification_list') site_name = get_site_name() # start now = datetime.now() today = datetime.now().replace(hour=0).replace(minute=0).replace( second=0).replace(microsecond=0) # 1. get all users who are connected dingtalk socials = SocialAuthUser.objects.filter(provider='dingtalk') users = [(x.username, x.uid) for x in socials] self.log_info('Found %d users' % len(users)) if not users: return user_uid_map = {} for username, uid in users: user_uid_map[username] = dingtalk_get_userid_by_unionid(uid) # 2. get previous time that command last runs try: cmd_last_check = CommandsLastCheck.objects.get( command_type=self.label) self.log_debug('Last check time is %s' % cmd_last_check.last_check) last_check_dt = cmd_last_check.last_check cmd_last_check.last_check = now cmd_last_check.save() except CommandsLastCheck.DoesNotExist: last_check_dt = today self.log_debug('Create new last check time: %s' % now) CommandsLastCheck(command_type=self.label, last_check=now).save() # 3. get all unseen notices for those users qs = UserNotification.objects.filter( timestamp__gt=last_check_dt).filter(seen=False).filter( to_user__in=list(user_uid_map.keys())) self.log_info('Found %d notices' % qs.count()) if qs.count() == 0: return user_notices = {} for q in qs: if q.to_user not in user_notices: user_notices[q.to_user] = [q] else: user_notices[q.to_user].append(q) # save current language cur_language = translation.get_language() # active zh-cn translation.activate('zh-cn') self.log_info('the language is set to zh-cn') # 4. send msg to users for username, uid in users: user_id = user_uid_map[username] notices = user_notices.get(username, []) count = len(notices) if count == 0: continue title = ungettext( "\n" "You've got 1 new notice on %(site_name)s:\n", "\n" "You've got %(num)s new notices on %(site_name)s:\n", count) % { 'num': count, 'site_name': site_name, } content = ' \n '.join( [remove_html_a_element(x.format_msg()) for x in notices]) self.send_dingtalk_msg(user_id, title, content) # reset language translation.activate(cur_language) self.log_info('reset language success')
def do_action(self): if not ENABLE_DINGTALK and not ENABLE_WORK_WEIXIN: self.log_info('No social account enabled') return dingtalk_access_token = '' work_weixin_access_token = '' if ENABLE_DINGTALK: dingtalk_access_token = dingtalk_get_access_token() if not dingtalk_access_token: self.log_error('can not get access token for dingtalk') else: self.dingtalk_message_send_to_conversation_url = DINGTALK_MESSAGE_SEND_TO_CONVERSATION_URL + \ '?access_token=' + dingtalk_access_token self.detail_url = get_site_scheme_and_netloc().rstrip( '/') + reverse('user_notification_list') if ENABLE_WORK_WEIXIN: work_weixin_access_token = get_work_weixin_access_token() if not work_weixin_access_token: self.log_error('can not get access token for work weixin') else: self.work_weixin_notifications_url = WORK_WEIXIN_NOTIFICATIONS_URL + \ '?access_token=' + work_weixin_access_token self.detail_url = get_site_scheme_and_netloc().rstrip( '/') + reverse('user_notification_list') if not dingtalk_access_token and not work_weixin_access_token: return # save current language cur_language = translation.get_language() # active zh-cn translation.activate('zh-cn') self.log_info('the language is set to zh-cn') # 1. get previous time that command last runs now = datetime.now() today = datetime.now().replace(hour=0).replace(minute=0).replace( second=0).replace(microsecond=0) try: cmd_last_check = CommandsLastCheck.objects.get( command_type=self.label) self.log_debug('Last check time is %s' % cmd_last_check.last_check) last_check_dt = cmd_last_check.last_check cmd_last_check.last_check = now cmd_last_check.save() except CommandsLastCheck.DoesNotExist: last_check_dt = today self.log_debug('Create new last check time: %s' % now) CommandsLastCheck(command_type=self.label, last_check=now).save() # 2. get all unseen notices user_notifications = UserNotification.objects.filter( timestamp__gt=last_check_dt).filter(seen=False) self.log_info('Found %d notices' % user_notifications.count()) if user_notifications.count() == 0: return # 3. get all users should send notice to user_email_list = list( set([item.to_user for item in user_notifications])) dingtail_socials = SocialAuthUser.objects.filter( provider='dingtalk').filter(username__in=user_email_list) dingtalk_email_list = [item.username for item in dingtail_socials] dingtalk_email_uid_dict = {} for item in dingtail_socials: dingtalk_email_uid_dict[ item.username] = dingtalk_get_userid_by_unionid(item.uid) work_weixin_socials = SocialAuthUser.objects.filter(provider=WORK_WEIXIN_PROVIDER, \ uid__contains=WORK_WEIXIN_UID_PREFIX).filter(username__in=user_email_list) work_weixin_email_list = [ item.username for item in work_weixin_socials ] work_weixin_email_uid_dict = {} for item in work_weixin_socials: work_weixin_email_uid_dict[ item.username] = item.uid[len(WORK_WEIXIN_UID_PREFIX):] # 4. send msg site_name = get_site_name() for email in list(set(dingtalk_email_list + work_weixin_email_list)): should_send = [] for notification in user_notifications: if email == notification.to_user: should_send.append(notification) title = _("You've got %(num)s new notices on %(site_name)s:\n") % \ {'num': len(should_send), 'site_name': site_name, } has_sent = False if not has_sent and email in dingtalk_email_list and ENABLE_DINGTALK: content = ' \n '.join([ remove_html_a_element_for_dingtalk(x.format_msg()) for x in should_send ]) self.send_dingtalk_msg(dingtalk_email_uid_dict[email], title, content) has_sent = True if not has_sent and email in work_weixin_email_list and ENABLE_WORK_WEIXIN: content = ''.join([ wrap_div_for_work_weixin(x.format_msg()) for x in should_send ]) self.send_work_weixin_msg(work_weixin_email_uid_dict[email], title, content) has_sent = True translation.activate(cur_language) self.log_info('reset language success') return
def do_action( self): # todo: complete send-notices-email code, make it works now = datetime.datetime.now() try: cmd_last_check = CommandsLastCheck.objects.get( command_type=self.label) logger.debug('Last check time is %s' % cmd_last_check.last_check) unseen_notices = UserNotification.objects.get_all_notifications( seen=False, time_since=cmd_last_check.last_check) logger.debug('Update last check time to %s' % now) cmd_last_check.last_check = now cmd_last_check.save() except CommandsLastCheck.DoesNotExist: logger.debug('No last check time found, get all unread notices.') unseen_notices = UserNotification.objects.get_all_notifications( seen=False) logger.debug('Create new last check time: %s' % now) CommandsLastCheck(command_type=self.label, last_check=now).save() email_ctx = {} for notice in unseen_notices: if notice.to_user in email_ctx: email_ctx[notice.to_user] += 1 else: email_ctx[notice.to_user] = 1 for to_user, count in list(email_ctx.items()): # save current language cur_language = translation.get_language() # get and active user language user_language = self.get_user_language(to_user) translation.activate(user_language) logger.debug('Set language code to %s for user: %s' % (user_language, to_user)) self.stdout.write('[%s] Set language code to %s' % (str(datetime.datetime.now()), user_language)) notices = [] for notice in unseen_notices: if notice.to_user != to_user: continue logger.info('Processing unseen notice: [%s]' % (notice)) if notice.is_add_user_to_group_msg(): notice = self.format_add_user_to_group(notice) elif notice.is_share_dtable_to_user_msg(): notice = self.format_share_dtable_to_user_msg(notice) if notice is None: continue notices.append(notice) if not notices: continue contact_email = Profile.objects.get_contact_email_by_user(to_user) to_user = contact_email # use contact email if any c = { 'to_user': to_user, 'notice_count': count, 'notices': notices, } try: send_html_email( _('New notice on %s') % get_site_name(), 'notifications/notice_email.html', c, None, [to_user]) logger.info('Successfully sent email to %s' % to_user) self.stdout.write('[%s] Successfully sent email to %s' % (str(datetime.datetime.now()), to_user)) except Exception as e: logger.error('Failed to send email to %s, error detail: %s' % (to_user, e)) self.stderr.write( '[%s] Failed to send email to %s, error detail: %s' % (str(datetime.datetime.now()), to_user, e)) # restore current language translation.activate(cur_language)