This repository has been archived by the owner on Oct 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.rb
100 lines (78 loc) · 2.13 KB
/
app.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
88
89
90
91
92
93
94
95
96
97
98
99
100
require 'bundler'
Bundler.require
require 'sinatra'
require 'yaml'
$config = YAML.load_file('config.yml')
module Application
class Frontend < Sinatra::Base
before do
@name = $config['name']
end
get '/' do
erb :index
end
post '/check' do
content_type :json
date = DateTime.parse(params[:date]).to_date
range = [date.to_datetime, (date+1).to_datetime]
events = Application::State.events
.find_all { |event| Application::State.event_on_date(event, date, range) }
.map { |event| { 'start' => event.dtstart, 'end' => event.dtend } }
return {
events: events
}.to_json
end
post '/schedule' do
date = DateTime.parse(params[:date]).to_date
range = [date.to_datetime, (date+1).to_datetime]
@events = Application::State.events
.find_all { |event| Application::State.event_on_date(event, date, range) }
.sort_by(&:dtstart)
erb :schedule
end
# Download copies of all the calendars
get '/sync' do
Application::State.sync!
204
end
end
module State
extend self
def events
@events ||= get_events
end
def sync!
calendars = $config['calendars']
calendars.each do |calendar|
digest = Digest::MD5.hexdigest(calendar['uri'])
File.open("tmp/calendar-#{digest}.ics", 'w') do |file|
open(calendar['uri']) do |resource|
file.write(resource.read)
end
end
end
@events = nil
events
end
def event_on_date(event, date, range = nil)
unless range
range = [date.to_datetime, (date+1).to_datetime]
end
return true if event.dtstart.to_date == date
return true if event.occurrences(overlapping: range).count > 0
return false
end
private
def get_events
events = []
Dir.glob('tmp/calendar-*.ics').each do |path|
File.open(path) do |file|
# FIXME: iCal allows multiple calendars per file
calendar = RiCal.parse(file).first
events += calendar.events
end
end
return events
end
end
end