-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathline_logger.rb
87 lines (72 loc) · 2.69 KB
/
line_logger.rb
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
module LineLogger
require 'pathname'
require 'fileutils'
require "rexml/document"
$:.push('.')
require 'linegui'
require 'line_message'
class Logger
attr_reader :management, :folder, :revision
def initialize(management, folder = ".")
@management = management
@folder = folder
@revision = nil
end
def add_message(message)
id = nil
if message.to == @management.get_own_user_id()
id = message.from
else
id = message.to
end
File.open("#{folder}/#{id}.log", 'a') do |f| f.puts(message_to_xml(message)) end
end
def get_messages(id, limit = 50)
messages = []
begin
File.readlines("#{folder}/#{id}.log").reverse.each_with_index do |line, index|
if limit == nil or index < limit
doc = REXML::Document.new(line)
text = doc.root.elements["text"]
text = text.text.to_s unless text.nil?
from = doc.root.attributes["from"]
to = doc.root.attributes["to"]
id = doc.root.attributes["id"]
revision = doc.root.attributes["rev"]
if not revision.nil? and not revision.to_s.empty?
revision = revision.to_i
else
revision = nil
end
timestamp = doc.root.attributes["timestamp"]
sticker = doc.root.elements["sticker"]
if sticker != nil
sticker = LineMessage::Sticker.new(sticker.attributes["set_id"], sticker.attributes["version"], sticker.attributes["id"])
end
image = doc.root.elements["image"]
if image != nil
image = LineMessage::Image.new(image.attributes["id"], image.attributes["url"], image.attributes["preview_url"])
end
messages << LineMessage::Message.new(from, to, id, timestamp.to_i, text.nil? ? text : text.gsub("[\\n]", "\n"), sticker, image, revision, true)
unless revision.nil?
if @revision.nil? or @revision < revision
@revision = revision
end
end
end
end
rescue Errno::ENOENT
end
return messages.reverse
end
def message_to_xml(message)
return "<message rev=\"#{message.revision}\" id=\"#{message.id}\" from=\"#{message.from}\" to=\"#{message.to}\" timestamp=\"#{message.timestamp}\">#{message.sticker.nil? ? "" : sticker_to_xml(message.sticker)}#{message.image.nil? ? "" : image_to_xml(message.image)}#{message.text.nil? ? "" : "<text>#{message.text.encode(:xml => :text).gsub("\n", "[\\n]")}</text>"}</message>"
end
def sticker_to_xml(sticker)
return "<sticker set_id=\"#{sticker.set_id}\" version=\"#{sticker.version}\" id=\"#{sticker.id}\"/>"
end
def image_to_xml(image)
return "<image id=\"#{image.id}\"#{image.url.nil? ? "" : " url=\"#{image.url}\""}#{image.preview_url.nil? ? "" : " url=\"#{image.preview_url}\""}/>"
end
end
end