This repository was archived by the owner on Oct 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy patharchives.js
232 lines (199 loc) · 6.2 KB
/
archives.js
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
var EventEmitter = require('events')
var assert = require('assert')
var levelPromise = require('level-promise')
var createIndexer = require('level-simple-indexes')
var sublevel = require('subleveldown')
var collect = require('stream-collector')
var lock = require('../lock')
var { promisifyModule } = require('../helpers')
// exported api
// =
class ArchivesDB extends EventEmitter {
constructor (cloud) {
super()
this.config = cloud.config
this.archiver = cloud.archiver
this.usersDB = cloud.usersDB
// create levels and indexer
this.archivesDB = sublevel(cloud.db, 'archives', { valueEncoding: 'json' })
this.deadArchivesDB = sublevel(cloud.db, 'dead-archives')
this.indexDB = sublevel(cloud.db, 'archives-index')
this.indexer = createIndexer(this.indexDB, {
keyName: 'key',
properties: ['createdAt'],
map: (key, next) => {
this.getExtraByKey(key)
.catch(next)
.then(res => next(null, res))
}
})
// promisify
levelPromise.install(this.archivesDB)
promisifyModule(this.indexer, ['findOne', 'addIndexes', 'removeIndexes', 'updateIndexes'])
}
// basic ops
// =
async create (record) {
assert(record && typeof record === 'object')
assert(typeof record.key === 'string')
record = Object.assign({}, ArchivesDB.defaults(), record)
record.createdAt = Date.now()
await this.put(record)
await this.indexer.updateIndexes(record)
this.emit('create', record)
return record
}
async put (record) {
assert(typeof record.key === 'string')
record.updatedAt = Date.now()
await this.archivesDB.put(record.key, record)
this.emit('put', record)
}
async del (record) {
assert(record && typeof record === 'object')
assert(typeof record.key === 'string')
await this.archivesDB.del(record.key)
await this.indexer.removeIndexes(record)
/* dont await */ this.deadArchivesDB.del(record.key)
this.emit('del', record)
}
// getters
// =
async getByKey (key) {
assert(typeof key === 'string')
try {
return await this.archivesDB.get(key)
} catch (e) {
if (e.notFound) return null
throw e
}
}
async getOrCreateByKey (key) {
var release = await lock('archives:goc:' + key)
try {
var archiveRecord = await this.getByKey(key)
if (!archiveRecord) {
archiveRecord = await this.create({ key })
}
} finally {
release()
}
return archiveRecord
}
async getExtraByKey (key) {
var archive = this.archiver.archives[key]
var record = await this.getByKey(key)
if (record.hostingUsers[0]) {
record.owner = await this.usersDB.getByID(record.hostingUsers[0])
record.name = record.owner.archives.find(a => a.key === key).name
record.niceUrl = record.name === record.owner.username
? `${record.owner.username}.${this.config.hostname}`
: `${record.name}-${record.owner.username}.${this.config.hostname}`
} else {
record.owner = null
record.name = ''
record.niceUrl = null
}
record.numPeers = archive ? archive.numPeers : 0
record.manifest = archive ? await this.archiver.getManifest(archive.key) : null
return record
}
list ({cursor, limit, reverse, sort} = {}) {
// 'popular' uses a special index
if (sort === 'popular') {
return this._listPopular({cursor, limit, reverse})
}
return new Promise((resolve, reject) => {
var opts = {limit, reverse}
if (typeof cursor !== 'undefined') {
// set cursor according to reverse
if (reverse) opts.lt = cursor
else opts.gt = cursor
}
// fetch according to sort
var stream
if (sort === 'createdAt') stream = this.indexer.find('createdAt', opts)
else stream = this.archivesDB.createValueStream(opts)
// collect into an array
collect(stream, (err, res) => {
if (err) reject(err)
else resolve(res)
})
})
}
async _listPopular ({cursor, limit, reverse}) {
cursor = cursor || 0
limit = limit || 25
// slice and dice the index
var index = this.archiver.indexes.popular
if (reverse) index = index.slice().reverse()
index = index.slice(cursor, cursor + limit)
// fetch the record for each item
return Promise.all(index.map(indexEntry => (
this.getExtraByKey(indexEntry.key)
)))
}
// highlevel updates
// =
async addHostingUser (key, userId) {
// fetch/create record
var archiveRecord = await this.getOrCreateByKey(key)
// add user
if (archiveRecord.hostingUsers.includes(userId)) {
return // already hosting
}
// TEMPORARY
// only allow one hosting user per archive
if (archiveRecord.hostingUsers.length > 0) {
throw new Error('Cant add another user')
}
// update records
archiveRecord.hostingUsers.push(userId)
await this.put(archiveRecord)
this.emit('add-hosting-user', {key, userId}, archiveRecord)
// track dead archives
/* dont await */ this.updateDeadArchives(key, archiveRecord.hostingUsers.length)
}
async removeHostingUser (key, userId) {
// fetch/create record
var archiveRecord = await this.getOrCreateByKey(key)
// remove user
var index = archiveRecord.hostingUsers.indexOf(userId)
if (index === -1) {
return // not already hosting
}
archiveRecord.hostingUsers.splice(index, 1)
// update records
await this.put(archiveRecord)
this.emit('remove-hosting-user', {key, userId}, archiveRecord)
// track dead archives
/* dont await */ this.updateDeadArchives(key, archiveRecord.hostingUsers.length)
}
// internal tracking
// =
listDeadArchiveKeys () {
return new Promise((resolve, reject) => {
collect(this.deadArchivesDB.createKeyStream(), (err, res) => {
if (err) reject(err)
else resolve(res)
})
})
}
async updateDeadArchives (key, numHostingUsers) {
try {
if (numHostingUsers === 0) {
await this.deadArchivesDB.put(key, '')
} else {
await this.deadArchivesDB.del(key)
}
} catch (e) {}
}
}
module.exports = ArchivesDB
// default user-record values
ArchivesDB.defaults = () => ({
key: null,
hostingUsers: [],
updatedAt: 0,
createdAt: 0
})