aboutsummaryrefslogtreecommitdiff
path: root/juick-server-jdbc/src/main/java/com/juick/service/TagServiceImpl.java
blob: 18e9485c9f7f19e212da9a37bcedf18ace39d2a3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
/*
 * Copyright (C) 2008-2017, Juick
 *
 * 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 com.juick.service;

import com.juick.Tag;
import com.juick.server.helpers.TagStats;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.inject.Inject;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * Created by aalexeev on 11/13/16.
 */
@Repository
public class TagServiceImpl extends BaseJdbcService implements TagService {
    private static final Pattern TAGS_PATTERN1 = Pattern.compile("^(?:(?:\\*[^ \\r\\n\\t]+)|\\s)+$");
    private static final Pattern TAGS_PATTERN2 = Pattern.compile("^\\*([^ \\r\\n\\t]+)\\s+([\\s\\S]+)");
    private static final Pattern TAG_PATTERN = Pattern.compile("\\*([^ \\r\\n\\t]+)");

    private final MessagesService messagesService;

    @Inject
    public TagServiceImpl(JdbcTemplate jdbcTemplate, MessagesService messagesService) {
        super(jdbcTemplate, null);
        Assert.notNull(messagesService, "MessagesService must be initialized");
        this.messagesService = messagesService;
    }

    @Transactional(readOnly = true)
    @Override
    public com.juick.Tag getTag(final int tid) {
        List<Tag> list = getJdbcTemplate().query(
                "SELECT synonym_id,name FROM tags WHERE tag_id=?",
                (rs, num) -> {
                    Tag ret = new Tag(rs.getString(2));
                    ret.TID = tid;
                    ret.SynonymID = rs.getInt(1);
                    return ret;
                },
                tid);

        return list.isEmpty() ?
                null : list.get(0);
    }

    @Transactional
    @Override
    public com.juick.Tag getTag(final String tag, final boolean autoCreate) {
        if (StringUtils.isBlank(tag))
            return null;

        List<Tag> list = getJdbcTemplate().query(
                "SELECT tag_id, synonym_id, name FROM tags WHERE name = ?",
                (rs, rowNum) -> {
                    Tag ret1 = new Tag(rs.getString(3));
                    ret1.TID = rs.getInt(1);
                    ret1.SynonymID = rs.getInt(2);
                    return ret1;
                },
                tag);

        Tag ret = list.isEmpty() ?
                null : list.get(0);

        if (ret == null && autoCreate) {
            ret = new com.juick.Tag(tag);
            ret.TID = createTag(tag);
        }

        return ret;
    }

    @Override
    public List<Tag> getTags(final String[] tags, final boolean autoCreate) {
        if (ArrayUtils.isEmpty(tags))
            return Collections.emptyList();

        List<Tag> ret = new ArrayList<>();

        for (String tag : tags) {
            if (!tag.isEmpty()) {
                Tag t = getTag(tag, autoCreate);

                if (t != null)
                    ret.add(t);
            }
        }

        return ret.stream().distinct().collect(Collectors.toList());
    }

    @Transactional(readOnly = true)
    @Override
    public boolean getTagNoIndex(final int tagId) {
        List<Integer> list = getJdbcTemplate().queryForList(
                "SELECT noindex FROM tags WHERE tag_id=?", Integer.class, tagId);

        return !list.isEmpty() && list.get(0) == 1;
    }

    @Transactional
    @Override
    public int createTag(final String name) {
        KeyHolder holder = new GeneratedKeyHolder();
        getJdbcTemplate().update(
                con -> {
                    PreparedStatement stmt = con.prepareStatement(
                            "INSERT INTO tags(name) VALUES (?)",
                            Statement.RETURN_GENERATED_KEYS);
                    stmt.setString(1, name);
                    return stmt;
                },
                holder);

        return holder.getKey().intValue();
    }

    private class TagStatsMapper implements RowMapper<TagStats> {

        @Override
        public TagStats mapRow(ResultSet rs, int rowNum) throws SQLException {
            Tag t = new Tag(rs.getString(1));
            TagStats s = new TagStats();
            s.setTag(t);
            s.setUsageCount(rs.getInt(2));
            return s;
        }
    }

    @Transactional(readOnly = true)
    @Override
    public List<TagStats> getUserTagStats(final int uid) {
        return getJdbcTemplate().query(
                "SELECT tags.name,COUNT(messages.message_id) " +
                        "FROM (messages INNER JOIN messages_tags ON (messages.user_id=? " +
                        "AND messages.message_id=messages_tags.message_id)) " +
                        "INNER JOIN tags ON messages_tags.tag_id=tags.tag_id GROUP BY tags.tag_id ORDER BY tags.name ASC",
                new TagStatsMapper(),
                uid);
    }

    @Transactional(readOnly = true)
    @Override
    public List<String> getUserBLTags(final int uid) {
        return getJdbcTemplate().queryForList(
                "SELECT tags.name FROM tags INNER JOIN bl_tags " +
                        "ON (bl_tags.user_id = ? AND bl_tags.tag_id = tags.tag_id) ORDER BY tags.name",
                String.class, uid);
    }

    @Transactional(readOnly = true)
    @Override
    public List<String> getPopularTags() {
        return getJdbcTemplate().queryForList(
                "SELECT name FROM tags WHERE top=1 ORDER BY name ASC", String.class)
                .stream()
                .collect(Collectors.toList());
    }

    @Transactional(readOnly = true)
    @Override
    public List<TagStats> getTagStats() {
        return getJdbcTemplate().query(
                "SELECT tags.name,COUNT(DISTINCT messages.user_id) AS cnt " +
                        "FROM (messages INNER JOIN messages_tags ON (messages.ts>TIMESTAMPADD(DAY,-3,NOW()) " +
                        "AND messages.message_id=messages_tags.message_id)) " +
                        "INNER JOIN tags ON messages_tags.tag_id=tags.tag_id " +
                        "WHERE tags.tag_id NOT IN (SELECT tag_id FROM tags_ignore) " +
                        "GROUP BY tags.tag_id ORDER BY cnt DESC LIMIT 20", new TagStatsMapper());
    }

    @Transactional
    @Override
    public List<Tag> updateTags(final int mid, final Collection<Tag> newTags) {
        List<Tag> currentTags = getMessageTags(mid).stream()
                .map(TagStats::getTag).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(newTags))
            return currentTags;

        List<Integer> idsForDelete = newTags.stream()
                .filter(currentTags::contains)
                .map(tag -> tag.TID)
                .collect(Collectors.toList());

        if (!idsForDelete.isEmpty())
            getNamedParameterJdbcTemplate().update(
                    "DELETE FROM messages_tags WHERE message_id = :mid AND tag_id in (:ids)",
                    new MapSqlParameterSource().addValue("ids", idsForDelete).addValue("mid", mid));

        newTags.stream().filter(t -> !currentTags.contains(t))
                .forEach(t -> getJdbcTemplate().update("INSERT INTO messages_tags(message_id,tag_id) VALUES (?,?)", mid, t.TID));

        return getMessageTags(mid).stream()
                .map(TagStats::getTag).collect(Collectors.toList());
    }

    @Override
    public List<Tag> fromString(final String txt, final boolean tagsOnly) {
        Pattern tagsPattern = tagsOnly ? TAGS_PATTERN1 : TAGS_PATTERN2;

        if (tagsPattern.matcher(txt).matches()) {
            Matcher tagMatcher = TAG_PATTERN.matcher(txt);

            List<Tag> tags = new ArrayList<>();

            // TODO: process readonly, private, friends, public
            while (tagMatcher.find()) {
                for (int i = 1; i <= tagMatcher.groupCount(); i++)
                    tags.add(getTag(tagMatcher.group(i), true));
            }
            return tags;
        }
        return Collections.emptyList();
    }

    @Transactional(readOnly = true)
    @Override
    public List<TagStats> getMessageTags(final int mid) {
        return getJdbcTemplate().query(
                "SELECT tags.tag_id,synonym_id,name,stat_messages FROM tags " +
                        "INNER JOIN messages_tags ON (messages_tags.message_id = ? AND messages_tags.tag_id = tags.tag_id)",
                (rs, num) -> {
                    com.juick.Tag t = new com.juick.Tag(rs.getString(3));
                    t.TID = rs.getInt(1);
                    t.SynonymID = rs.getInt(2);
                    TagStats s = new TagStats();
                    s.setTag(t);
                    s.setUsageCount(rs.getInt(4));
                    return s;
                }, mid);
    }

    @Transactional(readOnly = true)
    @Override
    public List<Integer> getMessageTagsIDs(final int mid) {
        return getJdbcTemplate().queryForList(
                "SELECT tag_id FROM messages_tags WHERE message_id = ?",
                Integer.class, mid);
    }
}