kulmapaikka-ircbot/plugins/mastodon.js

84 lines
2.3 KiB
JavaScript
Raw Normal View History

var Promise = require('promise')
var requestPromise = require('./helpers/requestPromise.js')
var BasePlugin = require('./base.js')
var htmlToText = require('html-to-text')
2017-10-18 23:17:20 +03:00
class Mastodon extends BasePlugin {
constructor (config) {
super(config)
this.name = 'Mastodon'
2017-10-18 23:17:20 +03:00
}
test (input) {
if (input.match(/http(s)?:\/\/(www\.)?((.*\..*\/users\/([a-zA-Z0-9_-]*)\/statuses\/([0-9_-]*)))/)) {
return true
2017-10-18 23:17:20 +03:00
}
if (input.match(/http(s)?:\/\/(www\.)?(((.*\..*)\/@([a-zA-Z0-9_-]*)\/([0-9_-]*)))/)) {
return true
2017-10-18 23:17:20 +03:00
}
return false
2017-10-18 23:17:20 +03:00
}
getToot (host, statusId) {
var promise = new Promise(function (resolve, reject) {
var url = 'https://' + host + '/api/v1/statuses/' + statusId
2017-10-18 23:17:20 +03:00
requestPromise(url, {}, {
'Accept': 'application/json'
}).then(function (toot) {
if (!toot.error) {
var user = toot.account.username
var time = toot.created_at
var dateTime = new Date(time)
var dateTimeLocale = dateTime.toLocaleDateString('fi-FI') + ' ' + dateTime.getHours() + '.' + dateTime.getMinutes()
2017-10-18 23:17:20 +03:00
var tootContent = toot.content
tootContent = htmlToText.fromString(tootContent, {
2017-10-18 23:17:20 +03:00
wordwrap: false,
ignoreHref: true,
preserveNewlines: false
})
2017-10-18 23:17:20 +03:00
var str = '@' + user + ': "' + tootContent + '" (' + dateTimeLocale + ')'
str = str.replace(/(?:\r\n|\r|\n)/g, ' ')
2017-10-18 23:17:20 +03:00
resolve(str)
2017-10-18 23:17:20 +03:00
} else {
reject(new Error(''))
2017-10-18 23:17:20 +03:00
}
})
})
return promise
2017-10-18 23:17:20 +03:00
}
result (input) {
var that = this
var resultPromise = new Promise(function (resolve, reject) {
var host = null
var tootId = null
2017-10-18 23:17:20 +03:00
var res = input.match(/http(s)?:\/\/(www\.)?(((.*\..*)\/users\/([a-zA-Z0-9_-]*)\/statuses\/([0-9_-]*)))/)
if (res !== null) {
host = res[5]
tootId = res[7]
2017-10-18 23:17:20 +03:00
}
res = input.match(/http(s)?:\/\/(www\.)?(((.*\..*)\/@([a-zA-Z0-9_-]*)\/([0-9_-]*)))/)
if (res !== null) {
host = res[5]
tootId = res[7]
2017-10-18 23:17:20 +03:00
}
if (host !== null && tootId !== null) {
that.getToot(host, tootId).then(function (toot) {
resolve('Tuuttaus: ' + toot)
}, function () {
reject(new Error('Tuuttaus: Jokin virhe tapahtui'))
})
2017-10-18 23:17:20 +03:00
}
})
2017-10-18 23:17:20 +03:00
return resultPromise
2017-10-18 23:17:20 +03:00
}
}
module.exports = Mastodon