This repository was archived by the owner on Oct 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathpost-to-buffer.js
171 lines (152 loc) · 4.67 KB
/
post-to-buffer.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
const axios = require('axios')
const querystring = require('qs')
const _ = require('lodash')
const admin = require('firebase-admin')
const cowsay = require('cowsay')
const wrapAnsi = require('wrap-ansi')
const Table = require('cli-table')
const serviceAccount = JSON.parse(
Buffer.from(process.env.FIREBASE_SERVICE_ACCOUNT_BASE64, 'base64').toString(
'utf8'
)
)
const bufferAccessToken = process.env.BUFFER_ACCESS_TOKEN
if (!bufferAccessToken) throw new Error('Env BUFFER_ACCESS_TOKEN missing')
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: 'https://tech-events-calendar-th.firebaseio.com'
})
process.on('unhandledRejection', up => {
throw up
})
const MONTHS = 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(',')
const DAYS = 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(',')
function dateOf({ year, month, date }) {
return new Date(year, month - 1, date)
}
function dates(event) {
const formatDate = ({ year, month, date }) => {
const day = dateOf({ year, month, date }).getDay()
return `${MONTHS[month - 1]} ${date} (${DAYS[day]})`
}
const formatTime = t => `${t.hour}:${t.minute < 10 ? '0' : ''}${t.minute}`
const start = formatDate(event.start)
const end = formatDate(event.end)
const time =
event.time && event.time.length === 1
? `${formatTime(event.time[0].from)} ~ ${formatTime(event.time[0].to)}`
: ''
return `${start}${end !== start ? ` ~ ${end}` : ''}${time ? `, ${time}` : ''}`
}
function hashtags(tags) {
return tags.map(x => `#${x.replace(/[^a-zA-Z0-9_]/g, '')}`).join(' ')
}
function say(text) {
return cowsay.say({ text: wrapAnsi(text, 80, { hard: true }) })
}
async function post(event, postMode) {
if (!event) {
throw new Error('Must supply event')
}
const url = `https://calendar.thaiprogrammer.org/event/${event.id}`
const fbEventLink = event.links.filter(link =>
/https:\/\/(?:www|web)\.facebook\.com\/events\/\d+/.test(link.url)
)[0]
const fbEventUrl = fbEventLink && fbEventLink.url
const link = fbEventUrl || url
const location = event.location && event.location.title
const text = [
`[Event] ${event.title}`,
`${dates(event)}${location ? ` @ ${location}` : ''}`,
'',
`${event.summary}`,
`${hashtags([...event.categories, ...event.topics])}`,
...(fbEventUrl ? ['', url] : [])
].join('\n')
console.log('Text to be posted:')
console.log(say(`${text}\n\n${link}`))
console.log()
// Uncomment the next line for dry-run!
// return
const postData = querystring.stringify({
text,
profile_ids: ['5abf3ce205fbf6386e4cebc8'],
media: { link },
shorten: 'false',
access_token: bufferAccessToken
})
console.log('Post data:')
console.log(say(postData))
console.log('Setting status to POSTING...')
await admin
.database()
.ref(`buffer/events/${event.id}/status`)
.set('POSTING')
console.log('Posting...')
await axios.post('https://api.bufferapp.com/1/updates/create.json', postData)
console.log('Setting status to POSTED...')
await admin
.database()
.ref(`buffer/events/${event.id}/status`)
.set('POSTED')
console.log('Writing log...')
await admin
.database()
.ref(`buffer/logs`)
.push({
type: 'POST',
postMode,
date: new Date(),
eventId: event.id
})
}
function checkPostingCriteria(event, bufferData) {
const status = _.get(bufferData, ['events', event.id, 'status'])
if (!status) {
return { postMode: 'NEW', result: 'NEW EVENT' }
}
return { result: status }
}
async function main() {
try {
const response = await axios.get(
'https://thaiprogrammer-tech-events-calendar.spacet.me/calendar.json'
)
const bufferData = (await admin
.database()
.ref('buffer')
.once('value')).val()
const today = new Date()
today.setHours(0, 0, 0, 0)
const upcomingEvents = response.data.filter(e => dateOf(e.start) >= today)
const table = new Table({
head: ['event id', 'post', 'result']
})
const results = upcomingEvents.map(e => {
const { postMode, result } = checkPostingCriteria(e, bufferData)
return { postMode, result, event: e }
})
table.push(
...results.map(({ postMode, result, event }) => [
event.id,
postMode || '---',
result
])
)
console.log(table.toString())
for (const { postMode, event } of results) {
// eslint-disable-next-line no-await-in-loop
if (postMode) await post(event, postMode)
}
} catch (e) {
if (e.response) {
console.error('Received response:', e.response.data)
}
process.exitCode = 1
console.error(e.stack)
throw e
} finally {
process.exit(process.exitCode || 0)
}
}
main()