aboutsummaryrefslogtreecommitdiff
path: root/src/legacy/legacyMigrator.js
blob: 2c491e3812581d03388ee9a982a4ccc45a1101ea (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
const fs = require('fs');
const path = require('path');
const promisify = require('util').promisify;
const moment = require('moment');
const Eris = require('eris');

const knex = require('../knex');
const config = require('../config');
const jsonDb = require('./jsonDb');
const threads = require('../data/threads');

const {THREAD_STATUS, THREAD_MESSAGE_TYPE} = require('../data/constants');

const readDir = promisify(fs.readdir);
const readFile = promisify(fs.readFile);
const access = promisify(fs.access);
const writeFile = promisify(fs.writeFile);

async function migrate() {
  console.log('Migrating open threads...');
  await migrateOpenThreads();

  console.log('Migrating logs...');
  await migrateLogs();

  console.log('Migrating blocked users...');
  await migrateBlockedUsers();

  console.log('Migrating snippets...');
  await migrateSnippets();

  await writeFile(path.join(config.dbDir, '.migrated_legacy'), '');
}

async function shouldMigrate() {
  // If there is a file marking a finished migration, assume we don't need to migrate
  const migrationFile = path.join(config.dbDir, '.migrated_legacy');
  try {
    await access(migrationFile);
    return false;
  } catch (e) {}

  // If there are any old threads, we need to migrate
  const oldThreads = await jsonDb.get('threads', []);
  if (oldThreads.length) {
    return true;
  }

  // If there are any old blocked users, we need to migrate
  const blockedUsers = await jsonDb.get('blocked', []);
  if (blockedUsers.length) {
    return true;
  }

  // If there are any old snippets, we need to migrate
  const snippets = await jsonDb.get('snippets', {});
  if (Object.keys(snippets).length) {
    return true;
  }

  // If the log file dir exists and has logs in it, we need to migrate
  try {
    const files = await readDir(config.logDir);
    if (files.length > 1) return true; // > 1, since .gitignore is one of them
  } catch(e) {}

  return false;
}

async function migrateOpenThreads() {
  const bot = new Eris.Client(config.token);

  const toReturn = new Promise(resolve => {
    bot.on('ready', async () => {
      const oldThreads = await jsonDb.get('threads', []);

      const promises = oldThreads.map(async oldThread => {
        const existingOpenThread = await knex('threads')
          .where('channel_id', oldThread.channelId)
          .first();

        if (existingOpenThread) return;

        const oldChannel = bot.getChannel(oldThread.channelId);
        if (! oldChannel) return;

        const threadMessages = await oldChannel.getMessages(1000);
        const log = threadMessages.reverse().map(msg => {
          const date = moment.utc(msg.timestamp, 'x').format('YYYY-MM-DD HH:mm:ss');
          return `[${date}] ${msg.author.username}#${msg.author.discriminator}: ${msg.content}`;
        }).join('\n') + '\n';

        const newThread = {
          status: THREAD_STATUS.OPEN,
          user_id: oldThread.userId,
          user_name: oldThread.username,
          channel_id: oldThread.channelId,
          is_legacy: 1
        };

        const threadId = await threads.createThreadInDB(newThread);

        await knex('thread_messages').insert({
          thread_id: threadId,
          message_type: THREAD_MESSAGE_TYPE.LEGACY,
          user_id: oldThread.userId,
          user_name: '',
          body: log,
          is_anonymous: 0,
          created_at: moment.utc().format('YYYY-MM-DD HH:mm:ss')
        });
      });

      resolve(Promise.all(promises));
    });

    bot.connect();
  });

  await toReturn;

  bot.disconnect();
}

async function migrateLogs() {
  const logDir = config.logDir || `${__dirname}/../../logs`;
  const logFiles = await readDir(logDir);

  for (let i = 0; i < logFiles.length; i++) {
    const logFile = logFiles[i];
    if (! logFile.endsWith('.txt')) continue;

    const [rawDate, userId, threadId] = logFile.slice(0, -4).split('__');
    const date = `${rawDate.slice(0, 10)} ${rawDate.slice(11).replace('-', ':')}`;

    const fullPath = path.join(logDir, logFile);
    const contents = await readFile(fullPath, {encoding: 'utf8'});

    const newThread = {
      id: threadId,
      status: THREAD_STATUS.CLOSED,
      user_id: userId,
      user_name: '',
      channel_id: null,
      is_legacy: 1,
      created_at: date
    };

    await knex.transaction(async trx => {
      const existingThread = await trx('threads')
        .where('id', newThread.id)
        .first();

      if (existingThread) return;

      await trx('threads').insert(newThread);

      await trx('thread_messages').insert({
        thread_id: newThread.id,
        message_type: THREAD_MESSAGE_TYPE.LEGACY,
        user_id: userId,
        user_name: '',
        body: contents,
        is_anonymous: 0,
        created_at: date
      });
    });

    // Progress indicator for servers with tons of logs
    if ((i + 1) % 500 === 0) {
      console.log(`  ${i + 1}...`);
    }
  }
}

async function migrateBlockedUsers() {
  const now = moment.utc().format('YYYY-MM-DD HH:mm:ss');
  const blockedUsers = await jsonDb.get('blocked', []);

  for (const userId of blockedUsers) {
    const existingBlockedUser = await knex('blocked_users')
      .where('user_id', userId)
      .first();

    if (existingBlockedUser) return;

    await knex('blocked_users').insert({
      user_id: userId,
      user_name: '',
      blocked_by: null,
      blocked_at: now
    });
  }
}

async function migrateSnippets() {
  const now = moment.utc().format('YYYY-MM-DD HH:mm:ss');
  const snippets = await jsonDb.get('snippets', {});

  const promises = Object.entries(snippets).map(async ([trigger, data]) => {
    const existingSnippet = await knex('snippets')
      .where('trigger', trigger)
      .first();

    if (existingSnippet) return;

    return knex('snippets').insert({
      trigger,
      body: data.text,
      is_anonymous: data.isAnonymous ? 1 : 0,
      created_by: null,
      created_at: now
    });
  });

  return Promise.all(promises);
}

module.exports = {
  migrate,
  shouldMigrate,
};