nora 0.1

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: e715c379310ef757bb3966ac8ad8e7acfdaea0b3
4
+ data.tar.gz: 3ab1d31c524fbd4a5ca36b1cd6dba635e76f3c78
5
+ SHA512:
6
+ metadata.gz: 50db09d25467fa6932c0f83f3af3b37863f000bde246dc9618645c8b8c85fa6aff72fa9e2ab0abe3c0f347f9a35b7d6b7268cb2429f25d1174e2af8e55b5dad6
7
+ data.tar.gz: bd4095e283356bf8229ff51e510dd0822e8c9498c6bd98b438afcf64654b19f9c74f0ce1012cc62298382ff0a38e5acaf5648e6b11613724a33e26255c02fdc2
data/.gitignore ADDED
@@ -0,0 +1,15 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ .DS_Store
11
+ nora_client_secret.json
12
+ nora_configuration.json
13
+ past_pairings.txt
14
+ calendar-ruby-quickstart.yaml
15
+ *.gem
data/.overcommit.yml ADDED
@@ -0,0 +1,57 @@
1
+ verify_signatures: false
2
+ CommitMsg:
3
+ CapitalizedSubject:
4
+ enabled: true
5
+ HardTabs:
6
+ enabled: true
7
+ RussianNovel:
8
+ enabled: true
9
+ SingleLineSubject:
10
+ enabled: true
11
+ TextWidth:
12
+ enabled: true
13
+ TrailingPeriod:
14
+ enabled: true
15
+ PreCommit:
16
+ ALL:
17
+ problem_on_unmodified_line: "warn"
18
+ AuthorEmail:
19
+ enabled: true
20
+ AuthorName:
21
+ enabled: true
22
+ Brakeman: # Performs static code security checking.
23
+ enabled: true
24
+ BrokenSymlinks:
25
+ enabled: true
26
+ BundleCheck:
27
+ enabled: false
28
+ CssLint:
29
+ enabled: true
30
+ HamlLint:
31
+ enabled: true
32
+ HardTabs:
33
+ enabled: true
34
+ HtmlTidy: # Uses the `tidy` executable (installed on OS X by default).
35
+ enabled: true
36
+ JsonSyntax:
37
+ enabled: true
38
+ LocalPathsInGemfile:
39
+ enabled: false
40
+ MergeConflicts:
41
+ enabled: true
42
+ PryBinding:
43
+ enabled: true
44
+ Reek:
45
+ enabled: false
46
+ RuboCop:
47
+ enabled: true
48
+ problem_on_unmodified_line: warn
49
+ ScssLint:
50
+ enabled: true
51
+ TrailingWhitespace:
52
+ enabled: true
53
+ TravisLint: # Checks Travis CI configurations. We use Travis for our open-
54
+ # source repositories.
55
+ enabled: true
56
+ YamlSyntax:
57
+ enabled: true
data/.rubocop.yml ADDED
@@ -0,0 +1,284 @@
1
+ require:
2
+ - rubocop/rspec/focused
3
+
4
+ # This (http://c2.com/cgi/wiki?AbcMetric) is super obnoxious
5
+ AbcSize:
6
+ Enabled: false
7
+
8
+ AccessorMethodName:
9
+ Enabled: false
10
+
11
+ Alias:
12
+ Enabled: false
13
+
14
+ AllCops:
15
+ Exclude:
16
+ - !ruby/regexp /vendor\/(?!panoramaed).*$/
17
+ - "spec/dummy/**/*"
18
+ - "db/schema.rb"
19
+ - "db/migrate/**/*"
20
+ TargetRubyVersion: 2.3
21
+
22
+ AmbiguousOperator:
23
+ Enabled: false
24
+
25
+ AmbiguousRegexpLiteral:
26
+ Enabled: false
27
+
28
+ ArrayJoin:
29
+ Enabled: false
30
+
31
+ AsciiComments:
32
+ Enabled: false
33
+
34
+ AsciiIdentifiers:
35
+ Enabled: false
36
+
37
+ AssignmentInCondition:
38
+ Enabled: true
39
+
40
+ Attr:
41
+ Enabled: false
42
+
43
+ BlockNesting:
44
+ Enabled: false
45
+
46
+ BracesAroundHashParameters:
47
+ Enabled: false
48
+
49
+ CaseEquality:
50
+ Enabled: false
51
+
52
+ CharacterLiteral:
53
+ Enabled: false
54
+
55
+ ClassLength:
56
+ Enabled: false
57
+
58
+ ClassVars:
59
+ Enabled: false
60
+
61
+ CollectionMethods:
62
+ PreferredMethods:
63
+ find: detect
64
+ reduce: inject
65
+ collect: map
66
+ find_all: select
67
+
68
+ ColonMethodCall:
69
+ Enabled: false
70
+
71
+ CommentAnnotation:
72
+ Enabled: false
73
+
74
+ ConditionPosition:
75
+ Enabled: false
76
+
77
+ CyclomaticComplexity:
78
+ Enabled: false
79
+
80
+ Debugger:
81
+ Enabled: true
82
+ Severity: error
83
+
84
+ Delegate:
85
+ Enabled: false
86
+
87
+ DeprecatedClassMethods:
88
+ Enabled: false
89
+
90
+ Documentation:
91
+ Enabled: false
92
+
93
+ DotPosition:
94
+ EnforcedStyle: trailing
95
+
96
+ DoubleNegation:
97
+ Enabled: false
98
+
99
+ ElseLayout:
100
+ Enabled: false
101
+
102
+ EmptyLiteral:
103
+ Enabled: false
104
+
105
+ EmptyElse:
106
+ Enabled: false
107
+
108
+ Encoding:
109
+ Enabled: false
110
+
111
+ EvenOdd:
112
+ Enabled: false
113
+
114
+ FileName:
115
+ Enabled: false
116
+
117
+ FlipFlop:
118
+ Enabled: false
119
+
120
+ FormatString:
121
+ Enabled: false
122
+
123
+ FrozenStringLiteralComment:
124
+ Enabled: false
125
+
126
+ GlobalVars:
127
+ Enabled: false
128
+
129
+ GuardClause:
130
+ Enabled: false
131
+
132
+ HandleExceptions:
133
+ Enabled: false
134
+
135
+ IfUnlessModifier:
136
+ Enabled: false
137
+
138
+ IfWithSemicolon:
139
+ Enabled: false
140
+
141
+ InvalidCharacterLiteral:
142
+ Enabled: false
143
+
144
+ Lambda:
145
+ Enabled: false
146
+
147
+ LambdaCall:
148
+ Enabled: false
149
+
150
+ LineEndConcatenation:
151
+ Enabled: false
152
+
153
+ LineLength:
154
+ Max: 80
155
+
156
+ LiteralInCondition:
157
+ Enabled: false
158
+
159
+ LiteralInInterpolation:
160
+ Enabled: false
161
+
162
+ Loop:
163
+ Enabled: false
164
+
165
+ MethodLength:
166
+ Enabled: false
167
+
168
+ Metrics/BlockLength:
169
+ Enabled: false
170
+
171
+ ModuleFunction:
172
+ Enabled: false
173
+
174
+ NegatedIf:
175
+ Enabled: false
176
+
177
+ NegatedWhile:
178
+ Enabled: false
179
+
180
+ Next:
181
+ Enabled: false
182
+
183
+ NilComparison:
184
+ Enabled: false
185
+
186
+ Not:
187
+ Enabled: false
188
+
189
+ NumericLiterals:
190
+ Enabled: false
191
+
192
+ OneLineConditional:
193
+ Enabled: false
194
+
195
+ OpMethod:
196
+ Enabled: false
197
+
198
+ ParameterLists:
199
+ Enabled: false
200
+
201
+ ParenthesesAsGroupedExpression:
202
+ Enabled: false
203
+
204
+ PercentLiteralDelimiters:
205
+ PreferredDelimiters:
206
+ '%': '{}'
207
+
208
+ PerceivedComplexity:
209
+ Enabled: false
210
+
211
+ PerlBackrefs:
212
+ Enabled: false
213
+
214
+ PredicateName:
215
+ Enabled: false
216
+
217
+ PreferredHashMethods:
218
+ Enabled: false
219
+
220
+ Proc:
221
+ Enabled: false
222
+
223
+ RaiseArgs:
224
+ Enabled: false
225
+
226
+ RedundantReturn:
227
+ AllowMultipleReturnValues: true
228
+
229
+ RegexpLiteral:
230
+ Enabled: false
231
+
232
+ RequireParentheses:
233
+ Enabled: false
234
+
235
+ RSpec/Focused:
236
+ Enabled: true
237
+
238
+ SelfAssignment:
239
+ Enabled: false
240
+
241
+ SignalException:
242
+ EnforcedStyle: only_raise
243
+
244
+ SingleLineBlockParams:
245
+ Enabled: false
246
+
247
+ SingleLineMethods:
248
+ Enabled: false
249
+
250
+ SpecialGlobalVars:
251
+ Enabled: false
252
+
253
+ StringLiterals:
254
+ EnforcedStyle: double_quotes
255
+
256
+ Style/MultilineBlockChain:
257
+ Enabled: false
258
+
259
+ Style/TrailingCommaInArguments:
260
+ Enabled: false
261
+
262
+ Style/TrailingCommaInLiteral:
263
+ Enabled: false
264
+
265
+ Style/VariableInterpolation:
266
+ Enabled: true
267
+
268
+ TrivialAccessors:
269
+ Enabled: false
270
+
271
+ UnderscorePrefixedVariableName:
272
+ Enabled: false
273
+
274
+ Void:
275
+ Enabled: false
276
+
277
+ WhenThen:
278
+ Enabled: false
279
+
280
+ WhileUntilModifier:
281
+ Enabled: false
282
+
283
+ WordArray:
284
+ Enabled: false
data/.ruby-version ADDED
@@ -0,0 +1 @@
1
+ 2.3.0
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.0.0
4
+ before_install: gem install bundler -v 1.10.6
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in nora.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Panorama Education
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,112 @@
1
+ # NORA
2
+
3
+ NORA (named because she "brings P-A-NORA-M-A together") is a Ruby gem that
4
+ schedules meetings between coworkers and adds them to Google Calendar without
5
+ any work on the part of the coworkers.
6
+
7
+ We use these meetings (we call them "NORAs") to get to know one another better,
8
+ grab coffee, brainstorm new ideas... whatever tickles our fancy
9
+ at the time. But you can choose to be as strict or as loose about your
10
+ organization's NORAs as you like.
11
+
12
+ **NOTE: This code is experimental. It works for us, but if it doesn't work for
13
+ you we'd love to hear about it so we can make it better.**
14
+
15
+ ## Installation
16
+
17
+ 1. `gem install nora`
18
+ 2. Use [Google's Developer Console](https://console.developers.google.com/projectselector/apis/credentials)
19
+ to create a new project and a new OAuth 2.0 client ID for NORA to use. Download
20
+ that file and rename it `nora_client_secret.json`.
21
+ 3. Obtain a [SendGrid](https://sendgrid.com) username and password. (This is
22
+ used for sending emails when scheduling.) If you use Heroku, you can obtain a
23
+ username and password easily by adding the free SendGrid add-on and then using
24
+ the username and password that are set automatically in config variables.
25
+ 4. Copy the [`examples/nora_configuration.json`](https://github.com/panorama-ed/nora/blob/master/examples/nora_configuration.json) file from this repo into the folder from
26
+ which you intend to run the `nora` program. Edit the file to include the names
27
+ and email addresses you want, your SendGrid credentials, and any other changes
28
+ you like.
29
+ 5. While logged in to Google Calendar (as the user you intend to run NORA as,
30
+ which is most likely yourself), use the "Add a friend's/coworker's calendar"
31
+ box to add the calendars for everyone you added to your
32
+ `nora_configuration.json` file. *Note that this step may not be necessary but
33
+ not doing it can occasionally cause people to get skipped when scheduling.*
34
+
35
+ ## Usage
36
+
37
+ Once you've gone through the installation steps above, you can schedule meetings
38
+ by running this command in your shell/terminal/console from the directory that
39
+ contains your `nora_configuration.json` and `nora_client_secret.json` files:
40
+
41
+ ```bash
42
+ nora --weeks-ahead <how many weeks ahead to schedule>
43
+ ```
44
+
45
+ For example:
46
+
47
+ ```bash
48
+ nora --weeks-ahead 2
49
+ ```
50
+
51
+ NORA automatically keeps track of who's been scheduled together in the past via
52
+ the `past_pairings.txt` file, so that the same folks don't get scheduled
53
+ together often.
54
+
55
+ #### Adding/Removing People
56
+
57
+ To add someone for future scheduling, simply add their name and email address
58
+ to `nora_configuration.json`, and add them to your Google Calendar as you did in
59
+ installation step 5.
60
+
61
+ To remove someone, just remove them from `nora_configuration.json`.
62
+
63
+ ## Troubleshooting
64
+
65
+ #### NORA isn't scheduling someone!
66
+
67
+ Make sure that they're in the `nora_configuration.json` file with the correct
68
+ email address, and that you've also added their email to the Google Calendar of
69
+ the user running NORA (see installation step 5).
70
+
71
+ #### NORA is scheduling events at the same time as full-day events!
72
+
73
+ Unfortunately this is due to a bug in how Google Calendar calculates when
74
+ someone is "busy." See
75
+ [here](https://productforums.google.com/forum/#!topic/calendar/qAOwI540nu4) for
76
+ more details.
77
+
78
+ #### I'm seeing "Authorization failed" errors!
79
+
80
+ NOTE: If you consistently get errors that look like this:
81
+
82
+ ```
83
+ /Users/jacobevelyn/.gem/ruby/2.2.0/gems/signet-0.7.2/lib/signet/oauth_2/client.rb:981:in `fetch_access_token': Authorization failed. Server message: (Signet::AuthorizationError)
84
+ {
85
+ "error": "invalid_grant",
86
+ "error_description": "Bad Request"
87
+ }
88
+ from /Users/jacobevelyn/.gem/ruby/2.2.0/gems/signet-0.7.2/lib/signet/oauth_2/client.rb:998:in `fetch_access_token!'
89
+ ...
90
+ ```
91
+
92
+ then all you need to do is delete the credentials file and re-run the program.
93
+ This will create a new credentials file.
94
+
95
+ #### I have another question or issue!
96
+
97
+ No problem! Simply create a GitHub Issue and we'll get you straightened out.
98
+
99
+ ## Contributing
100
+
101
+ 1. Fork it (https://github.com/panorama-ed/nora/fork)
102
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
103
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
104
+ 4. Push to the branch (`git push origin my-new-feature`)
105
+ 5. Create a new Pull Request
106
+
107
+ **Make sure your changes conform to the Rubocop style specified.** We use
108
+ [overcommit](https://github.com/causes/overcommit) to enforce consistent code.
109
+
110
+ ## License
111
+
112
+ The gem is available as open source under the terms of the [MIT License](https://github.com/panorama-ed/nora/blob/master/LICENSE.txt).
data/exe/nora ADDED
@@ -0,0 +1,50 @@
1
+ #! /usr/bin/env ruby
2
+
3
+ require "optparse"
4
+
5
+ require_relative "../lib/nora.rb"
6
+
7
+ # @return [Hash] A hash of command line options:
8
+ # :weeks_ahead => How many weeks ahead to schedule
9
+ # :test => True iff we're testing the script (default: false)
10
+ def parsed_options
11
+ options = {}
12
+
13
+ parser = OptionParser.new do |opts|
14
+ opts.banner = "Usage: nora --weeks-ahead <weeks>"
15
+
16
+ opts.on(
17
+ "--weeks-ahead <weeks>",
18
+ "(required) How many weeks ahead to schedule"
19
+ ) do |weeks|
20
+ options[:weeks_ahead] = weeks.to_i
21
+ end
22
+
23
+ # Default to not using test mode
24
+ options[:test] = false
25
+
26
+ opts.on(
27
+ "--test",
28
+ "Testing mode. Does not actually schedule anything or send any emails."
29
+ ) do |test|
30
+ options[:test] = test
31
+ end
32
+
33
+ opts.on_tail("-h", "--help", "Show this message") do
34
+ puts opts
35
+ exit
36
+ end
37
+ end
38
+
39
+ parser.parse!
40
+
41
+ if !options[:weeks_ahead] || options[:weeks_ahead] < 1
42
+ puts "Missing argument: weeks-ahead"
43
+ puts parser
44
+ exit
45
+ end
46
+
47
+ options
48
+ end
49
+
50
+ Nora::Core.new(parsed_options).run!
data/lib/nora.rb ADDED
@@ -0,0 +1,5 @@
1
+ require "nora/core"
2
+ require "nora/version"
3
+
4
+ module Nora
5
+ end
data/lib/nora/core.rb ADDED
@@ -0,0 +1,380 @@
1
+ require "google/apis/calendar_v3"
2
+ require "googleauth"
3
+ require "googleauth/stores/file_token_store"
4
+
5
+ require "fileutils"
6
+
7
+ require "active_support"
8
+ require "active_support/core_ext/time/zones"
9
+ require "active_support/core_ext/numeric/time"
10
+ require "active_support/duration"
11
+ require "chronic"
12
+ require "pony"
13
+
14
+ module Nora
15
+ class Core
16
+ extend Memoist
17
+
18
+ PAIRINGS_FILE = "past_pairings.txt".freeze
19
+ PAIRINGS_FILE_SEPARATOR = " ".freeze
20
+
21
+ OOB_URI = "urn:ietf:wg:oauth:2.0:oob".freeze
22
+ CLIENT_SECRETS_PATH = "nora_client_secret.json".freeze
23
+ CREDENTIALS_PATH = "calendar-ruby-quickstart.yaml".freeze
24
+ SCOPE = Google::Apis::CalendarV3::AUTH_CALENDAR
25
+
26
+ FREE_BUSY_QUERY_BATCH_SIZE = 5
27
+
28
+ CONFIGURATION = JSON.parse(File.read("nora_configuration.json"))
29
+
30
+ Pony.options = {
31
+ via: :smtp,
32
+ via_options: {
33
+ address: "smtp.sendgrid.net",
34
+ port: "587",
35
+ domain: CONFIGURATION["email"]["domain"],
36
+ authentication: :plain,
37
+ enable_starttls_auto: true,
38
+
39
+ # These Sendgrid credentials come from the Heroku addon.
40
+ user_name:
41
+ CONFIGURATION["email"]["sendgrid_configuration"]["user_name"],
42
+ password: CONFIGURATION["email"]["sendgrid_configuration"]["password"],
43
+ }
44
+ }
45
+
46
+ def initialize(weeks_ahead:, test:)
47
+ puts
48
+
49
+ @weeks_ahead = weeks_ahead
50
+ @test = test
51
+
52
+ FileUtils.touch(PAIRINGS_FILE) # Make sure pairings file exists.
53
+
54
+ # Set global Chronic parsing time zone.
55
+ Time.zone = "UTC"
56
+ Chronic.time_class = Time.zone
57
+
58
+ # Initialize the API
59
+ @service = Google::Apis::CalendarV3::CalendarService.new
60
+ @service.client_options.application_name =
61
+ CONFIGURATION["calendar"]["application_name"]
62
+ @service.authorization = authorize
63
+ end
64
+
65
+ def run!
66
+ begin
67
+ load_history!
68
+ puts "Creating groups..."
69
+ create_groups!
70
+ rescue SystemStackError
71
+ remove_oldest_pair!
72
+
73
+ retry
74
+ end
75
+
76
+ send_emails(
77
+ template_emails_for(
78
+ schedule_meetings!
79
+ )
80
+ )
81
+
82
+ puts "Done."
83
+ end
84
+
85
+ private
86
+
87
+ def remove_oldest_pair!
88
+ puts "Removing oldest pair and retrying..."
89
+ File.open("past_pairings_tmp.txt", "w") do |file|
90
+ File.open(PAIRINGS_FILE).each.with_index(1) do |line, line_num|
91
+ file.puts(line) unless line_num == 1
92
+ end
93
+ end
94
+ FileUtils.mv("past_pairings_tmp.txt", PAIRINGS_FILE)
95
+ end
96
+
97
+ def load_history!
98
+ puts "Loading history..."
99
+ @history = Set.new
100
+ File.open(PAIRINGS_FILE).each do |line|
101
+ line.split(PAIRINGS_FILE_SEPARATOR).permutation.each do |emails|
102
+ @history << emails
103
+ end
104
+ end
105
+ end
106
+
107
+ def create_groups!
108
+ @emails = CONFIGURATION["people"].map { |p| p["email"] }.shuffle
109
+ @emails.each_slice(group_size).each do |emails|
110
+ return create_groups! unless (@history & emails.combination(2)).empty?
111
+ end
112
+ end
113
+
114
+ # @return [Array<Hash>] list of meetings, of the format:
115
+ # { on: <Time>, who: [{ email: ..., name: ... }, ...] }
116
+ def schedule_meetings!
117
+ puts "Scheduling meetings..."
118
+
119
+ meetings = []
120
+
121
+ @emails.each_slice(group_size) do |emails|
122
+ if emails.size < group_size
123
+ puts "\nNot enough people in group: #{emails}\n"
124
+ meetings << {
125
+ on: :no_group,
126
+ week_of: availability_schedule.keys.first,
127
+ who: emails.map do |email|
128
+ { email: email, name: email_name(email) }
129
+ end
130
+ }
131
+ next
132
+ end
133
+
134
+ time = availability_schedule.select do |_, ids|
135
+ ids.superset? Set.new(emails)
136
+ end.keys.sample
137
+
138
+ if time.nil?
139
+ puts "\nNo time found for #{emails}\n"
140
+ meetings << {
141
+ on: :no_time,
142
+ week_of: availability_schedule.keys.first,
143
+ who: emails.map do |email|
144
+ { email: email, name: email_name(email) }
145
+ end
146
+ }
147
+ else
148
+ puts "#{time} => #{emails}"
149
+ add_meeting(time: time, attendee_ids: emails)
150
+
151
+ unless @test
152
+ File.open(PAIRINGS_FILE, "a") do |file|
153
+ emails.combination(2) do |email_pair|
154
+ file.puts email_pair.join(PAIRINGS_FILE_SEPARATOR)
155
+ end
156
+ end
157
+ end
158
+
159
+ meetings << {
160
+ on: time,
161
+ who: emails.map do |email|
162
+ { email: email, name: email_name(email) }
163
+ end
164
+ }
165
+ end
166
+ end
167
+
168
+ meetings
169
+ end
170
+
171
+ def template_emails_for(appointments)
172
+ appointments.map do |appt|
173
+ names = appt[:who].map { |w| w[:name] }.join(" and ")
174
+
175
+ # rubocop:disable Style/MultilineMethodCallIndentation
176
+ message =
177
+ case appt[:on]
178
+ when :no_time
179
+ num_weeks = @weeks_ahead + 1
180
+ CONFIGURATION["email"]["templates"]["no_time"].
181
+ gsub("NAMES", names).
182
+ gsub("WEEKS_AHEAD", "#{num_weeks} #{'week'.pluralize(num_weeks)}")
183
+ when :no_group
184
+ num_weeks = @weeks_ahead + 1
185
+ CONFIGURATION["email"]["templates"]["no_group"].
186
+ gsub("WEEKS_AHEAD", "#{num_weeks} #{'week'.pluralize(num_weeks)}")
187
+ else
188
+ datetime = appt[:on].in_time_zone("Eastern Time (US & Canada)")
189
+ day = datetime.strftime("%B %-d")
190
+ military_time = datetime.strftime("%H%M")
191
+
192
+ CONFIGURATION["email"]["templates"]["default"].
193
+ gsub("NAMES", names).
194
+ gsub("DAY", day).
195
+ gsub("MILITARY_TIME", military_time).
196
+ gsub("ICEBREAKER", icebreaker)
197
+ end
198
+ # rubocop:enable Style/MultilineMethodCallIndentation
199
+
200
+ {
201
+ to: appt[:who],
202
+ subject: "NORA: Mission Briefing",
203
+ body: message
204
+ }
205
+ end
206
+ end
207
+
208
+ def send_emails(email_messages)
209
+ return if @test
210
+
211
+ puts "Sending emails..."
212
+
213
+ email_messages.each do |msg|
214
+ msg[:to].each do |to|
215
+ begin
216
+ Pony.mail(
217
+ to: to[:email],
218
+ from: CONFIGURATION["email"]["from_address"],
219
+ subject: msg[:subject],
220
+ body: msg[:body],
221
+ via: :smtp,
222
+ charset: "UTF-8"
223
+ )
224
+ rescue => e
225
+ puts e
226
+ end
227
+ end
228
+ end
229
+ end
230
+
231
+ def add_meeting(time:, attendee_ids:)
232
+ return if @test
233
+
234
+ @service.insert_event(
235
+ CONFIGURATION["calendar"]["id"],
236
+ Google::Apis::CalendarV3::Event.new(
237
+ summary:
238
+ "NORA: #{attendee_ids.map { |id| email_name(id) }.join('/')}",
239
+ description: "Icebreaker question: #{icebreaker}",
240
+ start: Google::Apis::CalendarV3::EventDateTime.new(
241
+ date_time: time.to_datetime
242
+ ),
243
+ end: Google::Apis::CalendarV3::EventDateTime.new(
244
+ date_time: (
245
+ time + CONFIGURATION["calendar"]["duration_in_minutes"]
246
+ ).to_datetime
247
+ ),
248
+ attendees: attendee_ids.map do |id|
249
+ Google::Apis::CalendarV3::EventAttendee.new(email: id)
250
+ end,
251
+ guests_can_modify: true
252
+ )
253
+ )
254
+ end
255
+
256
+ def availability_schedule
257
+ # Compute Hash of all possible times to set of all user IDs.
258
+ # rubocop:disable Metrics/LineLength
259
+ all_availabilities = CONFIGURATION["calendar"]["days_of_week"].flat_map do |day|
260
+ # rubocop:enable Metrics/LineLength
261
+ CONFIGURATION["calendar"]["start_times"].map do |time|
262
+ Chronic.parse("#{@weeks_ahead} weeks from next #{day} #{time}").utc
263
+ end
264
+ end.each_with_object({}) do |time, h|
265
+ h[time] = Set.new(calendars.map(&:id))
266
+ end
267
+
268
+ # Remove user IDs due to business constraints.
269
+ calendars.each_slice(FREE_BUSY_QUERY_BATCH_SIZE) do |cals|
270
+ @service.query_freebusy(
271
+ Google::Apis::CalendarV3::FreeBusyRequest.new(
272
+ time_min: start_of_week.iso8601,
273
+ time_max: end_of_week.iso8601,
274
+ time_zone: "UTC",
275
+ items: cals.map { |cal| { id: cal.id } }
276
+ )
277
+ ).calendars.each do |id, free_busy|
278
+ free_busy.busy.each do |busy_period|
279
+ all_availabilities.each do |time, ids|
280
+ if (busy_period.start.to_time <= (
281
+ time + CONFIGURATION["calendar"]["duration_in_minutes"] -
282
+ 1.minute
283
+ )) && (busy_period.end.to_time >= (time + 1.minute))
284
+ ids.delete(id)
285
+ end
286
+ end
287
+ end
288
+ end
289
+ end
290
+
291
+ # Now remove hash values that have <2 IDs in their set.
292
+ all_availabilities.select { |_, ids| ids.size > 1 }
293
+ end
294
+ memoize :availability_schedule
295
+
296
+ def icebreaker
297
+ CONFIGURATION["icebreakers"].sample
298
+ end
299
+ memoize :icebreaker
300
+
301
+ def email_name(email)
302
+ email_name_map[email]
303
+ end
304
+
305
+ def email_name_map
306
+ CONFIGURATION["people"].each_with_object({}) do |data, h|
307
+ h[data["email"]] = data["name"]
308
+ end
309
+ end
310
+ memoize :email_name_map
311
+
312
+ def calendars
313
+ @service.list_calendar_lists.items.select do |calendar|
314
+ @emails.include? calendar.id
315
+ end
316
+ end
317
+ memoize :calendars
318
+
319
+ def start_of_week
320
+ Chronic.parse(
321
+ # rubocop:disable Metrics/LineLength
322
+ "#{@weeks_ahead} weeks from next #{CONFIGURATION['calendar']['days_of_week'].first} "\
323
+ "#{CONFIGURATION['calendar']['start_times'].first}"
324
+ # rubocop:enable Metrics/LineLength
325
+ )
326
+ end
327
+ memoize :start_of_week
328
+
329
+ def end_of_week
330
+ date_time = (
331
+ Chronic.parse(
332
+ # rubocop:disable Metrics/LineLength
333
+ "#{@weeks_ahead} weeks from next #{CONFIGURATION['calendar']['days_of_week'].last} "\
334
+ "#{CONFIGURATION['calendar']['start_times'].last}"
335
+ # rubocop:enable Metrics/LineLength
336
+ ) + CONFIGURATION["calendar"]["duration_in_minutes"].minutes
337
+ )
338
+
339
+ if date_time > start_of_week
340
+ date_time
341
+ else
342
+ date_time + 7.days
343
+ end
344
+ end
345
+ memoize :end_of_week
346
+
347
+ # Ensure valid credentials, either by restoring from the saved credentials
348
+ # files or intitiating an OAuth2 authorization. If authorization is
349
+ # required, the user will be instructed appropriately.
350
+ # @return [Google::Auth::UserRefreshCredentials] OAuth2 credentials
351
+ def authorize
352
+ FileUtils.mkdir_p(File.dirname(CREDENTIALS_PATH))
353
+
354
+ client_id = Google::Auth::ClientId.from_file(CLIENT_SECRETS_PATH)
355
+ token_store = Google::Auth::Stores::FileTokenStore.
356
+ new(file: CREDENTIALS_PATH)
357
+ authorizer = Google::Auth::UserAuthorizer.
358
+ new(client_id, SCOPE, token_store)
359
+ credentials = authorizer.
360
+ get_credentials(CONFIGURATION["calendar"]["user_id"])
361
+ if credentials.nil?
362
+ url = authorizer.get_authorization_url(base_url: OOB_URI)
363
+ puts "Open the following URL in the browser and enter the " +
364
+ "resulting code after authorization"
365
+ puts url
366
+ code = gets
367
+ credentials = authorizer.get_and_store_credentials_from_code(
368
+ user_id: CONFIGURATION["calendar"]["user_id"],
369
+ code: code,
370
+ base_url: OOB_URI
371
+ )
372
+ end
373
+ credentials
374
+ end
375
+
376
+ def group_size
377
+ CONFIGURATION["group_size"]
378
+ end
379
+ end
380
+ end
@@ -0,0 +1,3 @@
1
+ module Nora
2
+ VERSION = "0.1".freeze
3
+ end
data/nora.gemspec ADDED
@@ -0,0 +1,32 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "nora/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "nora"
8
+ spec.version = Nora::VERSION
9
+ spec.authors = ["Jacob Evelyn"]
10
+ spec.email = ["jevelyn@panoramaed.com"]
11
+
12
+ spec.summary = "Bringing P-A-NORA-M-A together."
13
+ spec.description = "Automatically schedule coffee dates with coworkers."
14
+ spec.homepage = "https://github.com/panorama-ed/nora"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_development_dependency "bundler", "~> 1.10"
25
+ spec.add_development_dependency "overcommit", "~> 0.38"
26
+ spec.add_development_dependency "rubocop", "~> 0.47"
27
+
28
+ spec.add_dependency "pony", "~> 1.11"
29
+ spec.add_dependency "activesupport", "~> 5.0"
30
+ spec.add_dependency "chronic", "~> 0.10"
31
+ spec.add_dependency "google-api-client", "~> 0.10"
32
+ end
metadata ADDED
@@ -0,0 +1,157 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: nora
3
+ version: !ruby/object:Gem::Version
4
+ version: '0.1'
5
+ platform: ruby
6
+ authors:
7
+ - Jacob Evelyn
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-03-27 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.10'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.10'
27
+ - !ruby/object:Gem::Dependency
28
+ name: overcommit
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '0.38'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '0.38'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rubocop
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '0.47'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '0.47'
55
+ - !ruby/object:Gem::Dependency
56
+ name: pony
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '1.11'
62
+ type: :runtime
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '1.11'
69
+ - !ruby/object:Gem::Dependency
70
+ name: activesupport
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '5.0'
76
+ type: :runtime
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '5.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: chronic
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - "~>"
88
+ - !ruby/object:Gem::Version
89
+ version: '0.10'
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - "~>"
95
+ - !ruby/object:Gem::Version
96
+ version: '0.10'
97
+ - !ruby/object:Gem::Dependency
98
+ name: google-api-client
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - "~>"
102
+ - !ruby/object:Gem::Version
103
+ version: '0.10'
104
+ type: :runtime
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - "~>"
109
+ - !ruby/object:Gem::Version
110
+ version: '0.10'
111
+ description: Automatically schedule coffee dates with coworkers.
112
+ email:
113
+ - jevelyn@panoramaed.com
114
+ executables:
115
+ - nora
116
+ extensions: []
117
+ extra_rdoc_files: []
118
+ files:
119
+ - ".gitignore"
120
+ - ".overcommit.yml"
121
+ - ".rubocop.yml"
122
+ - ".ruby-version"
123
+ - ".travis.yml"
124
+ - CODE_OF_CONDUCT.md
125
+ - Gemfile
126
+ - LICENSE.txt
127
+ - README.md
128
+ - exe/nora
129
+ - lib/nora.rb
130
+ - lib/nora/core.rb
131
+ - lib/nora/version.rb
132
+ - nora.gemspec
133
+ homepage: https://github.com/panorama-ed/nora
134
+ licenses:
135
+ - MIT
136
+ metadata: {}
137
+ post_install_message:
138
+ rdoc_options: []
139
+ require_paths:
140
+ - lib
141
+ required_ruby_version: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - ">="
144
+ - !ruby/object:Gem::Version
145
+ version: '0'
146
+ required_rubygems_version: !ruby/object:Gem::Requirement
147
+ requirements:
148
+ - - ">="
149
+ - !ruby/object:Gem::Version
150
+ version: '0'
151
+ requirements: []
152
+ rubyforge_project:
153
+ rubygems_version: 2.5.1
154
+ signing_key:
155
+ specification_version: 4
156
+ summary: Bringing P-A-NORA-M-A together.
157
+ test_files: []