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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
require 'uri'
require 'open-uri'
require 'open_uri_redirections'
require 'nokogiri'
require 'cinch'
require 'sqlite3'
require 'time-lord'
require 'json'
require 'mastodon'
require 'yaml'

$db = SQLite3::Database.new "sotd.db"

rows = $db.execute <<-SQL
  CREATE TABLE IF NOT EXISTS sotd (
    id INTEGER PRIMARY KEY,
    username varchar(32),
    nick varchar(32),
    link TEXT,
    display TEXT,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  );
SQL

$config = YAML::load_file('/home/caff/code/sotdbot/config/config.yml')

SotdHelp = Class.new do
  include Cinch::Plugin

  match "sotdhelp"
  match "rollcall"
  match("sotdbot: help", {
    :use_prefix => false
  })

  def execute(m)
    m.reply "SOTDBot keeps track of your songs of the day. You can update your SOTD by running !supdate <link>, where link is a YouTube, Soundcloud, Archive.org, Monstercat, Spotify, or Bandcamp link, and !sotd retrieves the latest SOTDs, !sotd <username> gets the last SOTD by that user, and !sotdstats gets the top users of sotdbot. Also, !allmysotd <page> will retrieve your previous songs of the day, but must be messaged to sotdbot directly."
  end
end

module Invisibleify
  def self.invisibleify(str)
    str.gsub(/(..?)(.+)/, "\\1\u{200C}\\2")
  end
end

module SotdParse
  def self.parse(link)
    @display = ""
    if !link.host || !link.port then
      return 1
    elsif /youtu(?:be)?\.(?:be|com)/i =~ link.host then
      @doc = Nokogiri::HTML(open(link.to_s, :allow_redirections => :safe), nil, "UTF-8")
      @display = @doc.css("title")[0].content.sub(/\s-\sYouTube$/, '')
    elsif /bandcamp\.com/ =~ link.host then
      @doc = Nokogiri::HTML(open(link.to_s, :allow_redirections => :safe))
      @name = @doc.css(".trackTitle")[0].content.strip
      @artist = @doc.css("[itemprop='byArtist']")[0].content.strip
      @display = "#{@artist} - #{@name}"
    elsif /soundcloud\.com/ =~ link.host then
      @doc = Nokogiri::HTML(open(link.to_s, :allow_redirections => :safe))
      @display = @doc.css("[itemprop='name']")[0].content.sub(/\W+/, ' ').strip
    elsif /archive\.org/ =~ link.host then
      @doc = Nokogiri::HTML(open(link.to_s, :allow_redirections => :safe), nil, "UTF-8")
      # @display = @doc.css("title")[0].content.split(":")[0].strip
      @artist = @doc.css(".details-metadata [itemprop='creator']")[0].content.strip
      @title = @doc.css(".details-metadata [itemprop='name']")[0].content.strip
      @display = "#{@artist} - #{@title}"
    elsif /monstercat\.com/ =~ link.host and /release\/.+/ =~ link.path then
      @release = /release\/([A-Za-z0-9]+)/.match(link.path).captures[0]
      @data = JSON.parse(open("https://connect.monstercat.com/api/catalog/release/#{@release}", :allow_redirections => :safe).read)
      @display = "#{@data["renderedArtists"]} - #{@data["title"]}"
    elsif /vimeo\.com/ =~ link.host then
      @doc = Nokogiri::HTML(open(link.to_s, :allow_redirections => :safe))
      @display = @doc.css("meta[property='og:title']")[0]["content"]
    elsif /open.spotify.com/ =~ link.host then
      @doc = Nokogiri::HTML(open(link.to_s, :allow_redirections => :safe))
      @title = @doc.css(".media-bd h1")[0].content.strip
      @artist = @doc.css(".media-bd h2 a")[0].content.strip
      @display = "#{@artist} - #{@title}"
    else
      return 2
    end
    return @display
  end
end

SotdTest = Class.new do
  include Cinch::Plugin
  extend SotdParse

  match /sotdtest (.+)/

  def execute(m, link)
    @link = URI.parse(link)
    @display = SotdParse.parse(@link)
    if @display == 2 then
      m.reply "No valid parser found."
    elsif @display == 1 then
      m.reply "Invalid link."
    else
      m.reply "Link parsed to this display: #{@display}"
    end
  end
end

RegenHTML = Class.new do
  include Cinch::Plugin

  match "regenhtml"

  def execute(m)
    if m.user.user == "~caff" then
      @rows = $db.execute "SELECT sotd.username, sotd.display, sotd.link, sotd.created_at FROM sotd ORDER BY sotd.username DESC, sotd.created_at DESC"
      @rows.each do |row|
        filename = "/home/caff/public_html/sotd/.partials/#{row[0]}.mustache"
        html = "<tr><td><a href=\"#{row[2]}\">#{row[1]}</a></td><td>#{row[3]}</td></tr>"
        File.open(filename, "a") { |f| f.write(html) }
      end
    end
  end
end

SotdUpdate = Class.new do
  include Cinch::Plugin
  extend SotdParse

  match /supdate ([^ ]+)(?: (.+))?/
  match /sotd (https?:\/\/[^ ]+)(?: (.+))?/
  match /sotdupdate ([^ ]+)(?: (.+))?/

  def execute(m, link, desc)
    @link = URI.parse(link)
    unless desc
      @display = SotdParse.parse(@link)
    else
      @display = desc
    end
    if @display == 2 then
      m.reply "This doesn't look like a supported link. Let ~caff know if this should be added, or rerun SOTD adding a title to this link. !supdate <link> <title>"
    elsif @display == 1 then
      m.reply "This doesn't appear to be a valid link. Sorry!"
    elsif !@display.is_a? String then
      m.reply "Something seems to have gone wrong. Let ~caff know."
    else
      rows = $db.execute "insert into sotd ( username, nick, link, display ) VALUES ( ?, ?, ?, ? )", [m.user.user, m.user.nick, @link.to_s, @display]
      client = Mastodon::REST::Client.new(base_url: 'https://tiny.tilde.website', bearer_token: $config['mastodon']['access_token'])
      client.create_status("#{m.user.user} has updated their #SOTD: #{@display} <#{@link.to_s}>")
      m.reply "Done! Your song of the day has been updated to #{@display}"
    end
  end
end

class SotdStats
  include Cinch::Plugin
  extend Invisibleify

  match "sotdstats"

  def execute(m)
    rows = $db.execute <<-SQL
      SELECT username, COUNT(username) FROM sotd
        GROUP BY username
        ORDER BY COUNT(username) DESC
        LIMIT 10;
    SQL

    rep = rows.map { |r| "#{Invisibleify.invisibleify(r[0])}: #{r[1]}" }
    m.reply "Top SOTD users: #{ rep * ", " }"
  end
end

class SotdGet
  include Cinch::Plugin
  extend Invisibleify

  match "sotd"
  match /sotd ([a-zA-Z0-9]+)/

  def execute(m, username = "")
    if username.to_s.empty? then
      rows = $db.execute <<-SQL
        SELECT sotd.username, sotd.display, sotd.link, sotd.created_at
        FROM sotd sotd
        INNER JOIN (
          SELECT MAX(created_at) created_at, username
          FROM sotd
          WHERE created_at > DATETIME('now', '-2 days')
          GROUP BY username
        ) AS s1
          ON sotd.username = s1.username
          AND sotd.created_at = s1.created_at
        ORDER BY sotd.created_at DESC
      SQL
      rows.each do |row|
        time = DateTime.parse(row[3]).to_time
        period = TimeLord::Period.new(time, Time.now).to_words
        m.reply "#{Invisibleify.invisibleify(row[0])}: #{row[1]} <#{row[2]}> (#{period})"
        sleep 0.25
      end
    else
      rows = $db.execute <<-SQL
        SELECT username, display, link, created_at
        FROM sotd
        WHERE username='#{username}' OR username='~#{username}'
        ORDER BY created_at DESC
        LIMIT 1;
      SQL
      rows.each do |row|
        time = DateTime.parse(row[3]).to_time
        period = TimeLord::Period.new(time, Time.now).to_words
        m.reply "#{Invisibleify.invisibleify(row[0])}: #{row[1]} <#{row[2]}> (#{period})"
        sleep 0.25
      end
    end
  end
end

class SotdAll
  include Cinch::Plugin

  match /allmysotd(?: (\d+))?/

  def execute(m, page = 0)
    if m.channel? then
      return m.reply "Please message this command to me directly as it is quite verbose. Try /msg sotdbot !allmysotd <page>"
    end
    page ||= 1
    page = [page.to_i - 1, 0].max
    pagelength = 10.to_f
    usercount = $db.execute "SELECT COUNT(*) FROM SOTD WHERE username='#{m.user.user}' LIMIT 1;"
    count = usercount[0][0]
    @totalpages = count / pagelength
    @totalpages = @totalpages.ceil
    if count < (page.to_i * pagelength) then
      return m.reply "No more pages."
    else
      rows = $db.execute <<-SQL
        SELECT display, link, created_at
        FROM sotd
        WHERE username='#{m.user.user}'
        ORDER BY created_at DESC
        LIMIT #{pagelength}
        OFFSET #{pagelength * page};
      SQL

      rows.each do |row|
        time = DateTime.parse(row[2]).to_time
        period = TimeLord::Period.new(time, Time.now).to_words
        m.reply "#{row[0]} <#{row[1]}> (#{period})"
        sleep 0.25
      end
      m.reply("Page #{page + 1} of #{@totalpages} (#{count} songs total)")
    end
  end
end

bot = Cinch::Bot.new do
  configure do |c|
    c.server = "tilde.town"
    if ARGV.include? "--debug" then
      c.channels = ["#sotd"]
    else
      c.channels = ["#tildetown", "#bots", "#sotd", "#music"]
    end
    c.nick = "sotdbot"
    c.realname = "sotdbot"
    c.user = "sotdbot"
    c.plugins.prefix = "!"
    c.plugins.plugins = [
      SotdHelp, SotdUpdate, SotdStats, SotdGet, SotdTest, SotdAll, RegenHTML
    ]
  end
end

bot.start