<commit_before>/*
 * Copyright (C) 2013-2016 Université Toulouse 3 <NAME>
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Affero General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Affero General Public License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.tsaap.notes

import grails.plugin.mail.MailService
import groovy.sql.Sql
import org.hibernate.SessionFactory
import org.springframework.context.MessageSource
import org.tsaap.directory.UnsubscribeKey

import javax.sql.DataSource

class ResponseNotificationService {

    static transactional = false

    MailService mailService
    DataSource dataSource
    SessionFactory sessionFactory
    MessageSource messageSource
    UnsubscribeKey key

    /**
     * Send mails to users mentioned in the last 5 minutes
     *
     * @return
     */
    def notifyUsersOnResponsesAndMentions() {
        Map notificationsMentions = findAllMentionsAndResponsesNotifications()

        if (notificationsMentions.size() > 0) {
            notificationsMentions.each { userId, map ->

                def sub = messageSource.getMessage("email.mention.notification.title", null, new Locale(map.language))
                try {
                    mailService.sendMail {
                        to map.email
                        subject sub
                        html view: "/email/responsesNotification", model: [user        : [user: map.user, language: map.language, first_name: map.first_name, email: map.email],
                                                                           mentionsList: map.mentionsList,
                                                                           key         : map.key]
                    }
                } catch (Exception e) {
                    log.error("Error with ${map.email} : ${e.message}")
                }
            }
        }
    }

    /**
     * Find notifications of users mentioned in the last 5 minutes
     *
     * @return a map with the user as key, and information and all notifications about the user as value
     */
    Map findAllMentionsAndResponsesNotifications() {
        def sql = new Sql(sessionFactory.currentSession.connection())
        def req = """
                SELECT distinct tmention.mention_id as receiver_id, tuser1.first_name, tuser1.email, tsettings.language, tcontext.id as context_id,
                tcontext.context_name, tnote.fragment_tag_id as tag_id, if((tnote.fragment_tag_id is null),null,ttag.name) tag_name, tuser2.username as author, tnote.content, tkey.unsubscribe_key as ukey
                FROM note_mention as tmention, note as tnote, context as tcontext, user as tuser1, user as tuser2, tag as ttag, settings as tsettings, unsubscribe_key as tkey
                WHERE tnote.date_created > date_sub(now(),interval 5 minute)
                and tnote.id = tmention.note_id
                AND tnote.context_id = tcontext.id
                and tnote.author_id != tmention.mention_id
                and tmention.mention_id = tuser1.id
                and tnote.author_id = tuser2.id
                and (tnote.fragment_tag_id is null or ttag.id = tnote.fragment_tag_id)
                and tuser1.id = tsettings.user_id
                and tsettings.mention_notifications = 1
                and tkey.user_id = tuser1.id
                and tcontext.closed = FALSE
                order by receiver_id
                """

        def rows = sql.rows(req)
        def notifications = [:]
        rows.each {
            def key = it.receiver_id
            if (notifications[key] == null) {
                notifications[key] = [key: it.ukey, first_name: it.first_name, email: it.email, language: it.language, mentionsList: []]<commit_msg>Replaced obsolete sql request method<commit_after>/*
 * Copyright (C) 2013-2016 Université Toulouse 3 <NAME>
 *
 *     This program is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU Affero General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 *
 *     This program is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU Affero General Public License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.tsaap.notes

import grails.plugin.mail.MailService
import groovy.sql.Sql
import org.hibernate.SessionFactory
import org.springframework.context.MessageSource
import org.tsaap.directory.UnsubscribeKey

import javax.sql.DataSource

class ResponseNotificationService {

    static transactional = false

    MailService mailService
    DataSource dataSource
    MessageSource messageSource
    UnsubscribeKey key

    /**
     * Send mails to users mentioned in the last 5 minutes
     *
     * @return
     */
    def notifyUsersOnResponsesAndMentions() {
        Map notificationsMentions = findAllMentionsAndResponsesNotifications()

        if (notificationsMentions.size() > 0) {
            notificationsMentions.each { userId, map ->

                def sub = messageSource.getMessage("email.mention.notification.title", null, new Locale(map.language))
                try {
                    mailService.sendMail {
                        to map.email
                        subject sub
                        html view: "/email/responsesNotification", model: [user        : [user: map.user, language: map.language, first_name: map.first_name, email: map.email],
                                                                           mentionsList: map.mentionsList,
                                                                           key         : map.key]
                    }
                } catch (Exception e) {
                    log.error("Error with ${map.email} : ${e.message}")
                }
            }
        }
    }

    /**
     * Find notifications of users mentioned in the last 5 minutes
     *
     * @return a map with the user as key, and information and all notifications about the user as value
     */
    Map findAllMentionsAndResponsesNotifications() {
        def sql = new Sql(dataSource)
        def req = """
                SELECT distinct tmention.mention_id as receiver_id, tuser1.first_name, tuser1.email, tsettings.language, tcontext.id as context_id,
                tcontext.context_name, tnote.fragment_tag_id as tag_id, if((tnote.fragment_tag_id is null),null,ttag.name) tag_name, tuser2.username as author, tnote.content, tkey.unsubscribe_key as ukey
                FROM note_mention as tmention, note as tnote, context as tcontext, user as tuser1, user as tuser2, tag as ttag, settings as tsettings, unsubscribe_key as tkey
                WHERE tnote.date_created > date_sub(now(),interval 5 minute)
                and tnote.id = tmention.note_id
                AND tnote.context_id = tcontext.id
                and tnote.author_id != tmention.mention_id
                and tmention.mention_id = tuser1.id
                and tnote.author_id = tuser2.id
                and (tnote.fragment_tag_id is null or ttag.id = tnote.fragment_tag_id)
                and tuser1.id = tsettings.user_id
                and tsettings.mention_notifications = 1
                and tkey.user_id = tuser1.id
                and tcontext.closed = FALSE
                order by receiver_id
                """

        def rows = sql.rows(req)
        def notifications = [:]
        rows.each {
            def key = it.receiver_id
            if (notifications[key] == null) {
                notifications[key] = [key: it.ukey, first_name: it.first_name, email: it.email, language: it.language, mentionsList: []]
{'fraction_non_alphanumeric': 0.0715888954518606, 'fraction_numerical': 0.005670407560543414, 'mean_word_length': 1.9989373007438895, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 13, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2405736', 'n_tokens_mistral': 2296, 'n_tokens_neox': 2183, 'n_words': 698}