aboutsummaryrefslogtreecommitdiffstats
path: root/lib/migrate.js
blob: 87e7ab603d0981fc13e91ebf2c352dfdb8a09d03 (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
import { err, l } from "$lib/logging";
import { types } from "$lib/payments";
import { archive, db, g } from "$lib/db";

let q = {};
async function migrate(id) {
  id = id.replace(/\s/g, "").toLowerCase();
  let user = JSON.parse(await archive.get(`user:${id}`));

  if (typeof user === "string") {
    id = user;
    user = JSON.parse(await archive.get(`user:${id}`));
  }

  if (user) {
    let { username } = user;
    username = username.replace(/\s/g, "").toLowerCase();
    l("migrating", username);
    let multi = await db
      .multi()
      .set(`user:${username}`, id)
      .set(`user:${user.pubkey}`, id)
      .set(`user:${id}`, JSON.stringify(user))
      .set(`${id}:contacts`, (await archive.get(`${id}:contacts`)) || "[]")
      .set(
        `credit:bitcoin:${id}`,
        (await archive.get(`credit:bitcoin:${id}`)) || 0,
      )
      .set(
        `credit:lightning:${id}`,
        (await archive.get(`credit:lightning:${id}`)) || 0,
      )
      .set(`${id}:lastlen`, (await archive.get(`${id}:lastlen`)) || 0)
      .set(`${id}:cindex`, (await archive.get(`${id}:cindex`)) || 0)
      .set(`balance:${id}`, (await archive.get(`balance:${id}`)) || 0)
      .set(`pending:${id}`, (await archive.get(`pending:${id}`)) || 0);

    let payments = await archive.lRange(`${id}:payments`, 0, -1);
    await Promise.all(
      payments.map(async (pid) => {
        let p = JSON.parse(await archive.get(`payment:${pid}`));
        if (p.type === types.internal && p.ref) {
          let recipient = await g(`user:${p.ref}`);
          if (!recipient) q[p.ref] = true;
        }

        multi = await multi
          .lPush(`${id}:payments`, pid)
          .set(`payment:${pid}`, JSON.stringify(p));
      }),
    );

    let invoices = await archive.lRange(`${id}:invoices`, 0, -1);
    await Promise.all(
      invoices.map(async (iid) => {
        let inv = await archive.get(`invoice:${iid}`);
        multi = await multi
          .lPush(`${id}:invoices`, iid)
          .set(`invoice:${iid}`, inv);
      }),
    );

    try {
      await multi.exec();
    } catch (e) {
      warn("failed to migrate", username);
    }

    delete q[id];

    console.log("SUCCESS", username);

    return user;
  }
}

let keepMigrating = async () => {
  try {
    if (Object.keys(q).length) {
      await migrate(Object.keys(q)[0]);
    }
  } catch (e) {
    err("problem migrating", e.message);
  }

  setTimeout(keepMigrating, 100);
};

keepMigrating();

export default migrate;