-
Notifications
You must be signed in to change notification settings - Fork 18
/
tweets-cleaner.js
88 lines (72 loc) · 2.45 KB
/
tweets-cleaner.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
'use strict'
const chalk = require('chalk')
const Twitter = require('twitter')
const jsonfile = require('jsonfile')
const config = require('./config')
function getTweets () {
global.window = { YTD: { tweets: { } } }
const tweets = require(config.path)
return window.YTD.tweets.part0.map(object => object.tweet)
}
const logFile = config.log || './log.json'
let log
try {
log = require(logFile)
} catch (e) {
console.log(chalk.cyan('No log file, starting a fresh delete cycle.'))
log = []
}
let maxDate = config.maxDate ? new Date(config.maxDate) : new Date()
const client = new Twitter({
consumer_key: config.consumer_key,
consumer_secret: config.consumer_secret,
access_token_key: config.access_token_key,
access_token_secret: config.access_token_secret
})
main()
function main () {
const rawTweets = getTweets()
const logIds = log.map(l => l.id)
const tweets = rawTweets.filter(t => {
const hasId = !isNaN(parseInt(t.id))
const oldEnough = new Date(t.created_at) < maxDate
const shouldBeSaved = config.saveRegexp.some((regexp) => new RegExp(regexp).test(t.full_text))
const notDeleted = logIds.indexOf(t.id) === -1
return hasId && oldEnough && notDeleted && !shouldBeSaved
})
if (!tweets || !tweets.length) {
return console.log(chalk.green('No more tweets to delete!'))
}
console.log(chalk.green(`Starting tweets cleaner on ${Date.now()} - Deleting tweets older than ${maxDate}`))
deleteTweet(tweets, 0)
}
function deleteTweet (tweets, i) {
let next = config.callsInterval
let remaining = 0
client.post('statuses/destroy', { id: tweets[i].id }, function (err, t, res) {
remaining = parseInt(res.headers['x-rate-limit-remaining'])
if (!isNaN(remaining) && remaining === 0) {
console.log(chalk.cyan('Waiting'))
next = parseInt(res.headers['x-rate-limit-reset']) - Date.now()
} else {
if (err) {
console.log(chalk.yellow(JSON.stringify(err)))
} else {
log.push(tweets[i])
console.log(chalk.green(`Deleted -> ${tweets[i].id} | ${tweets[i].full_text}`))
}
}
jsonfile.writeFile(logFile, log, { spaces: 2 }, function (err) {
if (err) {
return console.log(chalk.red('ERROR WRITING JSON!'))
}
if (i + 1 === tweets.length) {
return console.log(chalk.green('Done!'))
}
console.log(chalk.green(`Next call in ${next}ms`))
setTimeout(function () {
deleteTweet(tweets, i + 1)
}, next)
})
})
}