git ssb

0+

cel / ssb-wikimedia



Tree: 3f6da406d8217032f93b552b50bee8ca2384591a

Files: 3f6da406d8217032f93b552b50bee8ca2384591a / bin.js

12586 bytesRaw
1#!/usr/bin/env node
2
3var fs = require('fs')
4var path = require('path')
5var URL = require('url')
6var http = require('http')
7var https = require('https')
8var crypto = require('crypto')
9var readline = require('readline')
10var os = require('os')
11
12var ssbClient = require('ssb-client')
13var pull = require('pull-stream')
14
15var pkg = require('./package')
16
17var userAgentBase = pkg.name + '/' + pkg.version
18var userAgentContact
19var userAgentBot = false
20
21function estimateMessageSize(content) {
22 var draftMsg = {
23 key: '%0000000000000000000000000000000000000000000=.sha256',
24 value: {
25 previous: '%0000000000000000000000000000000000000000000=.sha256',
26 author: '@0000000000000000000000000000000000000000000=.ed25519',
27 sequence: 100000,
28 timestamp: 1000000000000.0001,
29 hash: 'sha256',
30 content: content,
31 signature: '00000000000000000000000000000000000000000000000000000000000000000000000000000000000000==.sig.ed25519'
32 }
33 }
34 return JSON.stringify(draftMsg, null, 2).length
35}
36
37function mapCollect(fn) {
38 var aborted
39 return function (read) {
40 var queue = []
41 return function (abort, cb) {
42 if (aborted = abort) return read(abort, cb)
43 read(null, function next(end, data) {
44 if (end) return cb(end)
45 queue.push(data)
46 var result = fn(queue)
47 if (result) read(null, next)
48 })
49 }
50 }
51}
52
53function getJson(url, cb) {
54 var opts = URL.parse(url)
55 opts.headers = {
56 'User-Agent': userAgentBase
57 + (userAgentContact ? ' (' + userAgentContact + ')' : '')
58 + (userAgentBot ? ' bot' : '')
59 }
60 var h = opts.protocol === 'https:' ? https : http
61 h.get(opts, function (res) {
62 if (res.statusCode !== 200) return cb(new Error('HTTP ' + res.statusCode + ' ' + res.statusMessage))
63 var bufs = []
64 res.on('data', function (buf) {
65 bufs.push(buf)
66 })
67 res.on('end', function () {
68 res.removeListener('error', cb)
69 var buf = Buffer.concat(bufs)
70 bufs = null
71 var data
72 try {
73 data = JSON.parse(buf.toString('utf8'))
74 } catch(e) {
75 return cb(e)
76 }
77 cb(null, data)
78 })
79 res.on('error', cb)
80 })
81}
82
83function publishDrafts(sbot, drafts, cb) {
84 var draftIdIndex = {}
85 drafts.forEach(function (draft, i) {
86 draftIdIndex[draft.draftId] = i
87 })
88 var ids = []
89
90 function replaceDraftIds(obj) {
91 if (typeof obj === 'string') {
92 var i = draftIdIndex[obj]
93 if (typeof i === 'number') {
94 var id = ids[i]
95 if (!id) throw new ReferenceError('draft referernces unknown message')
96 return id
97 }
98 } else if (Array.isArray(obj)) {
99 return obj.map(replaceDraftIds)
100 } else if (obj !== null && typeof obj === 'object') {
101 var o = {}
102 for (var k in obj) o[k] = replaceDraftIds(obj[k])
103 return o
104 }
105 return obj
106 }
107
108 pull(
109 pull.values(drafts),
110 pull.asyncMap(function (draft, cb) {
111 var content = replaceDraftIds(draft.content)
112 sbot.publish(content, function (err, msg) {
113 if (err) return cb(err)
114 ids.push(msg.key)
115 cb(null, msg)
116 })
117 }),
118 pull.collect(cb)
119 )
120}
121
122var args = process.argv.slice(2)
123var yes = false
124var dry = false
125var help = false
126var urls = []
127args.forEach(function (arg) {
128 if (arg[0] === '-') switch (arg) {
129 case '-n': return dry = true
130 case '-y': return yes = true
131 case '-h': return help = true
132 default: throw 'Unknown argument: ' + arg
133 } else urls.push(arg)
134})
135
136if (help) {
137 process.stdout.write(fs.readFileSync(path.join(__dirname, 'usage.txt')))
138 process.exit(0)
139}
140
141ssbClient(function (err, sbot, config) {
142 if (err) throw err
143 var conf = config.wikimedia || {}
144 userAgentContact = conf.contact
145 userAgentBot = conf.bot
146
147 if (urls.length === 0) {
148 var pagesFile = path.join(config.path, 'wikimedia-pages.txt')
149 var pagesData = fs.readFileSync(pagesFile, 'utf8')
150 urls = pagesData.split('\n').filter(RegExp.prototype.test.bind(/[^#]/))
151 if (!urls.length) {
152 console.log('No pages to sync.')
153 return sbot.close()
154 }
155 }
156
157 var pagesInfo = urls.map(function (page) {
158 var m = /^(.*?)\/wiki\/(.*)$/.exec(page)
159 if (!m) throw 'Unable to parse page URL ' + page
160 return {
161 site: m[1] + '/',
162 api: m[1] + '/w/api.php',
163 title: m[2]
164 }
165 })
166 var pagesInfoByApi = {}
167 pagesInfo.forEach(function (pageInfo) {
168 var infos = pagesInfoByApi[pageInfo.api] || (pagesInfoByApi[pageInfo.api] = [])
169 infos.push(pageInfo)
170 })
171 console.log('Normalizing titles...')
172 var waiting = 0
173 for (var api in pagesInfoByApi) (function (api) {
174 var pagesInfoForApi = pagesInfoByApi[api]
175 var pagesInfoForApiByTitle = {}
176 var titles = pagesInfoForApi.map(function (info) {
177 pagesInfoForApiByTitle[info.title] = info
178 return info.title
179 })
180 var url = api + '?format=json&action=query' +
181 '&titles=' + encodeURIComponent('\x1f' + titles.join('\x1f'))
182 waiting++
183 getJson(url, function (err, data) {
184 if (err) throw err
185 if (data.warnings) console.trace('Warnings:', data.warnings)
186 if (data.query.normalized) data.query.normalized.forEach(function (norm) {
187 var info = pagesInfoForApiByTitle[norm.from]
188 if (!info) {
189 console.error(JSON.stringify({titles: titles, response: data}, 0, 2))
190 throw new Error('Unexpected title in server response')
191 }
192 // console.log('Normalized title', norm.from, norm.to)
193 info.title = norm.to
194 })
195 if (!--waiting) next()
196 })
197 }(api))
198 function next() {
199 console.log('Getting revisions...')
200 pull(
201 pull.values(pagesInfo),
202 pull.asyncMap(function (pageInfo, cb) {
203 // Calculate blob id for page URL + title, for linking
204 pull(
205 pull.once(pageInfo.site + '\t' + pageInfo.title),
206 sbot.blobs.add(function (err, hash) {
207 pageInfo.hash = hash
208 cb(null, pageInfo)
209 })
210 )
211 }),
212 pull.asyncMap(function (pageInfo, cb) {
213 // Get previous messages for this page.
214 // Simple solution: find the revision with latest timestamp.
215 var maxRevTs = ''
216 var maxRevMsgId
217 pull(
218 sbot.links({
219 dest: pageInfo.hash,
220 rel: 'pageId',
221 values: true,
222 meta: false
223 }),
224 pull.filter(function (msg) {
225 var c = msg && msg.value && msg.value.content
226 return c
227 && c.type === 'wikimedia/revisions'
228 && c.site === pageInfo.site
229 && c.title === pageInfo.title
230 }),
231 pull.drain(function (msg) {
232 var c = msg && msg.value && msg.value.content
233 var revs = Array.isArray(c.revisions) && c.revisions
234 if (revs) revs.forEach(function (rev) {
235 if (rev && rev.timestamp > maxRevTs) {
236 maxRevTs = rev.timestamp
237 maxRevMsgId == msg.key
238 }
239 })
240 }, function (err) {
241 if (err) return cb(err)
242 pageInfo.latestMsgId = maxRevMsgId
243 pageInfo.latestRevTs = maxRevTs
244 cb(null, pageInfo)
245 })
246 )
247 }),
248 pull.map(function (pageInfo) {
249 // Get new revisions.
250 var rvcontinue, rvdone
251 var rvstart = pageInfo.latestRevTs
252 var prevId = pageInfo.latestMsgId
253 var aborted
254 var revisions = pull(
255 function (abort, cb) {
256 if (aborted = abort) return cb(abort)
257 if (rvdone) return cb(true)
258 console.log('Getting revisions for', pageInfo.title + '...',
259 rvstart || '', rvcontinue || '')
260 var url = api + '?format=json&action=query&prop=revisions&rvslots=*'
261 + '&titles=' + encodeURIComponent(pageInfo.title)
262 + '&rvprop=ids|timestamp|comment|user|slotsha1|slotsize|content|roles|flags|tags'
263 + '&rvdir=newer'
264 + (rvcontinue ? '&rvcontinue=' + rvcontinue : '')
265 + (rvstart ? '&rvstart=' + rvstart : '')
266 + '&rvlimit=50'
267 getJson(url, function (err, data) {
268 if (aborted) return err && console.trace(err)
269 if (err) return cb(err)
270 if (data.warnings) console.trace('Warnings:', data.warnings)
271 rvcontinue = data.continue && data.continue.rvcontinue
272 if (!rvcontinue) rvdone = true
273 var page
274 if (data.query) for (var pageid in data.query.pages) {
275 page = data.query.pages[pageid]
276 if (page.title === pageInfo.title) break
277 else page = null
278 }
279 if (!page) {
280 console.trace(data.query.pages, pageInfo)
281 return cb(new Error('Unable to find page'))
282 }
283 var revs = page.revisions
284 if (!revs) {
285 console.trace(page, pageInfo)
286 return cb(new Error('Unable to get revisions'))
287 }
288 console.log('Got ' + page.revisions.length + ' revisions')
289 cb(null, page.revisions)
290 })
291 },
292 pull.flatten(),
293 pull.asyncMap(function (rev, cb) {
294 var waiting = 0
295 for (var slot in rev.slots) (function (slot) {
296 waiting++
297 var slotInfo = rev.slots[slot]
298 var content = slotInfo['*']
299 if (!content) {
300 console.trace(slotInfo)
301 return cb(new Error('Missing content'))
302 }
303 var sha1 = crypto.createHash('sha1').update(content).digest('hex')
304 if (sha1 !== slotInfo.sha1) {
305 console.trace(slotInfo, sha1)
306 return cb(new Error('Mismatched content sha1'))
307 }
308 pull(
309 pull.once(content),
310 sbot.blobs.add(function (err, hash) {
311 if (err) return cb(err)
312 slotInfo.link = hash
313 delete slotInfo['*']
314 if (!--waiting) cb(null, rev)
315 })
316 )
317 }(slot))
318 })
319 )
320
321 var queuedRevisions = []
322 var ended
323 function cbDraft(content, cb) {
324 if (!content.revisions.length) {
325 console.log('No revisions for', pageInfo.title)
326 return cb(true)
327 }
328 console.log('Prepared a message',
329 'with', content.revisions.length, 'revisions',
330 'for', pageInfo.title)
331 prevId = '%' + crypto.createHash('sha256').update(JSON.stringify(content)).digest('base64') + '.draft6'
332 cb(null, {
333 draftId: prevId,
334 content: content
335 })
336 }
337 return function (abort, cb) {
338 if (abort) return revisions(abort, cb)
339 if (ended) return cb(true)
340 var content = {
341 type: 'wikimedia/revisions',
342 site: pageInfo.site,
343 title: pageInfo.title,
344 pageId: pageInfo.hash,
345 parents: prevId ? [prevId] : undefined,
346 revisions: queuedRevisions.splice(0)
347 }
348 revisions(null, function next(end, revision) {
349 if (ended = end) return cbDraft(content, cb)
350 content.revisions.push(revision)
351 if (estimateMessageSize(content) > 8192) {
352 queuedRevisions.push(content.revisions.pop())
353 // console.log('filled msg for ', pageInfo.title, ' with ', content.revisions.length, 'revisions')
354 return cbDraft(content, cb)
355 }
356 revisions(null, next)
357 })
358 }
359 }),
360 pull.flatten(),
361 pull.collect(function (err, drafts) {
362 if (err) throw err
363 if (dry) {
364 console.log(JSON.stringify(drafts, 0, 2))
365 return sbot.close()
366 }
367 if (yes) return confirmed(true)
368 var rl = readline.createInterface({
369 input: process.stdin,
370 output: process.stdout
371 })
372 rl.question('Publish ' + drafts.length + ' messages? [Y/n] ', function (answer) {
373 rl.close()
374 confirmed(!/^n/i.test(answer))
375 })
376 function confirmed(yes) {
377 if (!yes) return sbot.close()
378 publishDrafts(sbot, drafts, function (err, msgs) {
379 if (err) throw err
380 console.log('Published:\n' + msgs.map(function (msg) {
381 return msg.key
382 }.join('\n')))
383 sbot.close()
384 })
385 }
386 })
387 )
388 }
389})
390

Built with git-ssb-web