Skip to content

Commit 68ebeba

Browse files
committedJun 13, 2021
0.0.1
0 parents  commit 68ebeba

33 files changed

+1210
-0
lines changed
 

‎.github/workflows/main.yml

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
name: Ruby
2+
3+
on: [push,pull_request]
4+
5+
jobs:
6+
build:
7+
runs-on: ubuntu-latest
8+
steps:
9+
- uses: actions/checkout@v2
10+
- name: Set up Ruby
11+
uses: ruby/setup-ruby@v1
12+
with:
13+
ruby-version: 3.0.1
14+
- name: Install dependencies
15+
run: |
16+
gem install bundler
17+
bundle install
18+
- name: Rubocop
19+
run: bundle exec rubocop
20+
- name: RSpec
21+
env:
22+
GOOGLE_CLIENT_ID: ${{ secrets.GOOGLE_CLIENT_ID }}
23+
GOOGLE_CLIENT_SECRET: ${{ secrets.GOOGLE_CLIENT_SECRET }}
24+
GOOGLE_USERNAME: ${{ secrets.GOOGLE_USERNAME }}
25+
GOOGLE_REFRESH_TOKEN: ${{ secrets.GOOGLE_REFRESH_TOKEN }}
26+
run: bundle exec rspec

‎.gitignore

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
/.bundle/
2+
/.yardoc
3+
/_yardoc/
4+
/coverage/
5+
/doc/
6+
/pkg/
7+
/spec/reports/
8+
/tmp/
9+
10+
.env
11+
Gemfile.lock

‎.rspec

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
--format documentation
2+
--color
3+
--require spec_helper

‎.rubocop.yml

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
AllCops:
2+
TargetRubyVersion: 2.7
3+
NewCops: enable
4+
SuggestExtensions: false
5+
6+
Layout/LineLength:
7+
Max: 80
8+
9+
Metrics/AbcSize:
10+
Exclude:
11+
- 'lib/calendav/requests/*.rb'
12+
13+
Metrics/BlockLength:
14+
Exclude:
15+
- 'spec/**/*_spec.rb'
16+
17+
Metrics/MethodLength:
18+
Exclude:
19+
- 'lib/calendav/requests/*.rb'
20+
21+
Naming/RescuedExceptionsVariableName:
22+
PreferredName: error
23+
24+
Style/Documentation:
25+
Enabled: false
26+
27+
Style/StringLiterals:
28+
EnforcedStyle: double_quotes

‎CHANGELOG.md

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
## [Unreleased]
2+
3+
## [0.0.1] - 2021-06-13
4+
5+
An initial release with very limited (and likely buggy) support:
6+
7+
* Determining the principal URL.
8+
* Determining the calendar home path.
9+
* Listing available calendars.
10+
* Creating events on a calendar.
11+
* Listing events on a calendar within a given timespan.
12+
* Deleting events on a calendar.

‎CODE_OF_CONDUCT.md

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
# Contributor Covenant Code of Conduct
2+
3+
## Our Pledge
4+
5+
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6+
7+
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8+
9+
## Our Standards
10+
11+
Examples of behavior that contributes to a positive environment for our community include:
12+
13+
* Demonstrating empathy and kindness toward other people
14+
* Being respectful of differing opinions, viewpoints, and experiences
15+
* Giving and gracefully accepting constructive feedback
16+
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17+
* Focusing on what is best not just for us as individuals, but for the overall community
18+
19+
Examples of unacceptable behavior include:
20+
21+
* The use of sexualized language or imagery, and sexual attention or
22+
advances of any kind
23+
* Trolling, insulting or derogatory comments, and personal or political attacks
24+
* Public or private harassment
25+
* Publishing others' private information, such as a physical or email
26+
address, without their explicit permission
27+
* Other conduct which could reasonably be considered inappropriate in a
28+
professional setting
29+
30+
## Enforcement Responsibilities
31+
32+
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33+
34+
Community leaders 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, and will communicate reasons for moderation decisions when appropriate.
35+
36+
## Scope
37+
38+
This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39+
40+
## Enforcement
41+
42+
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at pat@freelancing-gods.com. All complaints will be reviewed and investigated promptly and fairly.
43+
44+
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45+
46+
## Enforcement Guidelines
47+
48+
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49+
50+
### 1. Correction
51+
52+
**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53+
54+
**Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55+
56+
### 2. Warning
57+
58+
**Community Impact**: A violation through a single incident or series of actions.
59+
60+
**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61+
62+
### 3. Temporary Ban
63+
64+
**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65+
66+
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67+
68+
### 4. Permanent Ban
69+
70+
**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71+
72+
**Consequence**: A permanent ban from any sort of public interaction within the community.
73+
74+
## Attribution
75+
76+
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77+
available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78+
79+
Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80+
81+
[homepage]: https://www.contributor-covenant.org
82+
83+
For answers to common questions about this code of conduct, see the FAQ at
84+
https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.

‎Gemfile

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
# frozen_string_literal: true
2+
3+
source "https://rubygems.org"
4+
5+
gemspec

‎LICENSE.md

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
Calendav Copyright (c) 2021 Pat Allan
2+
3+
Hippocratic License Version Number: 2.1.
4+
5+
Purpose. The purpose of this License is for the Licensor named above to permit the Licensee (as defined below) broad permission, if consistent with Human Rights Laws and Human Rights Principles (as each is defined below), to use and work with the Software (as defined below) within the full scope of Licensor’s copyright and patent rights, if any, in the Software, while ensuring attribution and protecting the Licensor from liability.
6+
7+
Permission and Conditions. The Licensor grants permission by this license (“License”), free of charge, to the extent of Licensor’s rights under applicable copyright and patent law, to any person or entity (the “Licensee”) obtaining a copy of this software and associated documentation files (the “Software”), to do everything with the Software that would otherwise infringe (i) the Licensor’s copyright in the Software or (ii) any patent claims to the Software that the Licensor can license or becomes able to license, subject to all of the following terms and conditions:
8+
9+
* Acceptance. This License is automatically offered to every person and entity subject to its terms and conditions. Licensee accepts this License and agrees to its terms and conditions by taking any action with the Software that, absent this License, would infringe any intellectual property right held by Licensor.
10+
11+
* Notice. Licensee must ensure that everyone who gets a copy of any part of this Software from Licensee, with or without changes, also receives the License and the above copyright notice (and if included by the Licensor, patent, trademark and attribution notice). Licensee must cause any modified versions of the Software to carry prominent notices stating that Licensee changed the Software. For clarity, although Licensee is free to create modifications of the Software and distribute only the modified portion created by Licensee with additional or different terms, the portion of the Software not modified must be distributed pursuant to this License. If anyone notifies Licensee in writing that Licensee has not complied with this Notice section, Licensee can keep this License by taking all practical steps to comply within 30 days after the notice. If Licensee does not do so, Licensee’s License (and all rights licensed hereunder) shall end immediately.
12+
13+
* Compliance with Human Rights Principles and Human Rights Laws.
14+
15+
1. Human Rights Principles.
16+
17+
(a) Licensee is advised to consult the articles of the United Nations Universal Declaration of Human Rights and the United Nations Global Compact that define recognized principles of international human rights (the “Human Rights Principles”). Licensee shall use the Software in a manner consistent with Human Rights Principles.
18+
19+
(b) Unless the Licensor and Licensee agree otherwise, any dispute, controversy, or claim arising out of or relating to (i) Section 1(a) regarding Human Rights Principles, including the breach of Section 1(a), termination of this License for breach of the Human Rights Principles, or invalidity of Section 1(a) or (ii) a determination of whether any Law is consistent or in conflict with Human Rights Principles pursuant to Section 2, below, shall be settled by arbitration in accordance with the Hague Rules on Business and Human Rights Arbitration (the “Rules”); provided, however, that Licensee may elect not to participate in such arbitration, in which event this License (and all rights licensed hereunder) shall end immediately. The number of arbitrators shall be one unless the Rules require otherwise.
20+
21+
Unless both the Licensor and Licensee agree to the contrary: (1) All documents and information concerning the arbitration shall be public and may be disclosed by any party; (2) The repository referred to under Article 43 of the Rules shall make available to the public in a timely manner all documents concerning the arbitration which are communicated to it, including all submissions of the parties, all evidence admitted into the record of the proceedings, all transcripts or other recordings of hearings and all orders, decisions and awards of the arbitral tribunal, subject only to the arbitral tribunal's powers to take such measures as may be necessary to safeguard the integrity of the arbitral process pursuant to Articles 18, 33, 41 and 42 of the Rules; and (3) Article 26(6) of the Rules shall not apply.
22+
23+
2. Human Rights Laws. The Software shall not be used by any person or entity for any systems, activities, or other uses that violate any Human Rights Laws. “Human Rights Laws” means any applicable laws, regulations, or rules (collectively, “Laws”) that protect human, civil, labor, privacy, political, environmental, security, economic, due process, or similar rights; provided, however, that such Laws are consistent and not in conflict with Human Rights Principles (a dispute over the consistency or a conflict between Laws and Human Rights Principles shall be determined by arbitration as stated above). Where the Human Rights Laws of more than one jurisdiction are applicable or in conflict with respect to the use of the Software, the Human Rights Laws that are most protective of the individuals or groups harmed shall apply.
24+
25+
3. Indemnity. Licensee shall hold harmless and indemnify Licensor (and any other contributor) against all losses, damages, liabilities, deficiencies, claims, actions, judgments, settlements, interest, awards, penalties, fines, costs, or expenses of whatever kind, including Licensor’s reasonable attorneys’ fees, arising out of or relating to Licensee’s use of the Software in violation of Human Rights Laws or Human Rights Principles.
26+
27+
* Failure to Comply. Any failure of Licensee to act according to the terms and conditions of this License is both a breach of the License and an infringement of the intellectual property rights of the Licensor (subject to exceptions under Laws, e.g., fair use). In the event of a breach or infringement, the terms and conditions of this License may be enforced by Licensor under the Laws of any jurisdiction to which Licensee is subject. Licensee also agrees that the Licensor may enforce the terms and conditions of this License against Licensee through specific performance (or similar remedy under Laws) to the extent permitted by Laws. For clarity, except in the event of a breach of this License, infringement, or as otherwise stated in this License, Licensor may not terminate this License with Licensee.
28+
29+
* Enforceability and Interpretation. If any term or provision of this License is determined to be invalid, illegal, or unenforceable by a court of competent jurisdiction, then such invalidity, illegality, or unenforceability shall not affect any other term or provision of this License or invalidate or render unenforceable such term or provision in any other jurisdiction; provided, however, subject to a court modification pursuant to the immediately following sentence, if any term or provision of this License pertaining to Human Rights Laws or Human Rights Principles is deemed invalid, illegal, or unenforceable against Licensee by a court of competent jurisdiction, all rights in the Software granted to Licensee shall be deemed null and void as between Licensor and Licensee. Upon a determination that any term or provision is invalid, illegal, or unenforceable, to the extent permitted by Laws, the court may modify this License to affect the original purpose that the Software be used in compliance with Human Rights Principles and Human Rights Laws as closely as possible. The language in this License shall be interpreted as to its fair meaning and not strictly for or against any party.
30+
31+
* Disclaimer. TO THE FULL EXTENT ALLOWED BY LAW, THIS SOFTWARE COMES “AS IS,” WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED, AND LICENSOR AND ANY OTHER CONTRIBUTOR SHALL NOT BE LIABLE TO ANYONE FOR ANY DAMAGES OR OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THIS LICENSE, UNDER ANY KIND OF LEGAL CLAIM.
32+
33+
This Hippocratic License is an Ethical Source license (https://ethicalsource.dev) and is offered for use by licensors and licensees at their own risk, on an “AS IS” basis, and with no warranties express or implied, to the maximum extent permitted by Laws.

‎README.md

+106
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
# Calendav
2+
3+
A library for interacting with CalDAV servers via Ruby.
4+
5+
At the time of writing, this gem is definitely not ready for production, nor is it anywhere close to supporting a decent set of features. Currently it covers the following:
6+
7+
* Determining the principal URL.
8+
* Determining the calendar home path.
9+
* Listing available calendars.
10+
* Creating events on a calendar.
11+
* Listing events on a calendar within a given timespan.
12+
* Deleting events on a calendar.
13+
14+
Other features on the roadmap, in a rough order of priority:
15+
16+
* Consistent access to calendar/event URLs.
17+
* Updating events.
18+
* List all events on a calendar.
19+
* Create new calendars.
20+
* Update calendars.
21+
* Delete calendars.
22+
* Enable etag validation for updates/deletions (If-Match header).
23+
* Solid exception handling.
24+
* Use WebDAV-Sync to get changes since last sync.
25+
* Enable locking/unlocking when making changes.
26+
* Allow requesting only certain properties for calendars/events.
27+
28+
Also, the plan is to have a test suite that covers multiple CalDAV server implementations.
29+
30+
## Usage
31+
32+
```ruby
33+
credentials = Calendav.credentials(
34+
:google, username: "example@gmail.com", password: "oauth-access-token"
35+
)
36+
# Also supported are FastMail and Apple, where the passwords should be
37+
# app-specific, with authentication via Basic Auth. Google uses a Bearer Token
38+
# for authentication (supplied as the password).
39+
#
40+
# Otherwise, to compose a more custom set of credentials:
41+
credentials = Calendav::Credentials::Standard.new(
42+
host: "https://www.example.com/caldav",
43+
username: "example",
44+
password: "secret",
45+
authentication: :basic_auth # or :bearer_token
46+
)
47+
48+
client = Calendav.client credentials
49+
puts client.principal_url
50+
51+
puts client.calendars.home_url
52+
calendars = client.calendars.list
53+
calendars.each { |calendar| puts calendar.path, calendar.display_name }
54+
55+
events = client.events.list(
56+
calendar.path, from: Time.new(2021, 1, 1), to: Time.new(2022, 1, 1)
57+
)
58+
59+
# use the icalendar gem to generate ICS strings
60+
ics = Icalendar::Calendar.new
61+
ics.event do |event|
62+
# ...
63+
end
64+
ics.publish
65+
66+
# You need to provide the expected filename for the event:
67+
identifier = "#{SecureRandom.uuid}.ics"
68+
# … but the server may change it on you, so the new, full URL is returned:
69+
event_url = client.events.create(calendar.path, identifier, ics.to_ical)
70+
71+
client.events.delete(event_url)
72+
```
73+
74+
## Installation
75+
76+
Add this line to your application's Gemfile:
77+
78+
```ruby
79+
gem 'calendav'
80+
```
81+
82+
And then execute:
83+
84+
$ bundle install
85+
86+
Or install it yourself as:
87+
88+
$ gem install calendav
89+
90+
## Development
91+
92+
After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
93+
94+
## Contributing
95+
96+
Bug reports and pull requests are welcome on GitHub at https://github.com/pat/calendav. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/pat/calendav/blob/main/CODE_OF_CONDUCT.md).
97+
98+
The test suite currently only runs against a Google account I've created especially for this purpose - and the credentials are not public. I realise this makes contributions more difficult, and I'm open to finding better ways to handle this. I did look into running a CalDAV server within the test suite, but couldn't find anything small and easy enough for that purpose. But also: testing against common CalDAV servers does help to ensure this gem is truly useful (and has knowledge of their idiosyncrasies).
99+
100+
## License
101+
102+
The gem is available as open source under the terms of the [Hippocratic License](https://firstdonoharm.dev).
103+
104+
## Code of Conduct
105+
106+
Everyone interacting in the Calendav project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/pat/calendav/blob/main/CODE_OF_CONDUCT.md).

‎Rakefile

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# frozen_string_literal: true
2+
3+
require "bundler/gem_tasks"
4+
require "rspec/core/rake_task"
5+
6+
RSpec::Core::RakeTask.new(:spec)
7+
8+
require "rubocop/rake_task"
9+
10+
RuboCop::RakeTask.new
11+
12+
task default: %i[spec rubocop]

‎bin/console

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#!/usr/bin/env ruby
2+
# frozen_string_literal: true
3+
4+
require "bundler/setup"
5+
require "calendav"
6+
7+
# You can add fixtures and/or initialization code here to make experimenting
8+
# with your gem easier. You can also use a different console, if you like.
9+
10+
# (If you use this, don't forget to add pry to your Gemfile!)
11+
# require "pry"
12+
# Pry.start
13+
14+
require "irb"
15+
IRB.start(__FILE__)

‎bin/setup

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
#!/usr/bin/env bash
2+
set -euo pipefail
3+
IFS=$'\n\t'
4+
set -vx
5+
6+
bundle install
7+
8+
# Do any other automated setup that you need to do here

‎calendav.gemspec

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
# frozen_string_literal: true
2+
3+
Gem::Specification.new do |spec|
4+
spec.name = "calendav"
5+
spec.version = "0.0.1"
6+
spec.authors = ["Pat Allan"]
7+
spec.email = ["pat@freelancing-gods.com"]
8+
9+
spec.summary = "CalDAV client"
10+
spec.homepage = "https://github.com/pat/calendav"
11+
spec.license = "Hippocratic-2.1"
12+
13+
spec.required_ruby_version = Gem::Requirement.new(">= 2.7.0")
14+
15+
spec.metadata["homepage_uri"] = spec.homepage
16+
spec.metadata["source_code_uri"] = spec.homepage
17+
spec.metadata["changelog_uri"] =
18+
"https://github.com/pat/calendav/blob/main/CHANGELOG.md"
19+
20+
spec.files = Dir["lib/**/*"] + %w[LICENSE.md README.md CHANGELOG.md]
21+
spec.test_files = Dir["spec/**/*"] + %w[.rspec Gemfile Rakefile]
22+
23+
spec.bindir = "exe"
24+
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
25+
spec.require_paths = ["lib"]
26+
27+
spec.add_runtime_dependency "http"
28+
spec.add_runtime_dependency "nokogiri"
29+
30+
spec.add_development_dependency "dotenv"
31+
spec.add_development_dependency "googleauth"
32+
spec.add_development_dependency "icalendar"
33+
spec.add_development_dependency "rake"
34+
spec.add_development_dependency "rspec"
35+
spec.add_development_dependency "rubocop"
36+
end

‎lib/calendav.rb

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# frozen_string_literal: true
2+
3+
require_relative "./calendav/credentials/apple"
4+
require_relative "./calendav/credentials/fastmail"
5+
require_relative "./calendav/credentials/google"
6+
require_relative "./calendav/client"
7+
8+
module Calendav
9+
PROVIDERS = {
10+
apple: Credentials::Apple,
11+
fastmail: Credentials::FastMail,
12+
google: Credentials::Google
13+
}.freeze
14+
15+
def self.credentials(provider, username, password)
16+
PROVIDERS.fetch(provider).new(username: username, password: password)
17+
end
18+
19+
def self.client(credentials)
20+
Client.new(credentials)
21+
end
22+
end

‎lib/calendav/calendar.rb

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# frozen_string_literal: true
2+
3+
require_relative "./xml_processor"
4+
5+
module Calendav
6+
class Calendar
7+
attr_reader :path
8+
9+
def self.from_xml(node)
10+
new(
11+
node.xpath("./dav:href").text,
12+
node.xpath(".//dav:prop/*").to_xml,
13+
node.namespaces
14+
)
15+
end
16+
17+
def initialize(path, attribute_nodes, namespaces = {})
18+
@path = path
19+
@attribute_nodes = attribute_nodes
20+
@namespaces = namespaces
21+
end
22+
23+
def display_name
24+
attribute_value fragment.xpath("//dav:displayname")
25+
end
26+
27+
def ctag
28+
attribute_value fragment.xpath("//cs:getctag")
29+
end
30+
31+
def etag
32+
attribute_value fragment.xpath("//dav:getetag")
33+
end
34+
35+
private
36+
37+
attr_reader :attribute_nodes, :namespaces
38+
39+
def fragment
40+
@fragment ||= XMLProcessor.call(
41+
"<nodes>#{attribute_nodes}</nodes>", namespaces
42+
)
43+
end
44+
45+
def attribute_value(node)
46+
return nil if node.children.empty?
47+
48+
if node.children.any?(&:element?)
49+
node.children.select(&:element?).collect(&:to_xml).join
50+
else
51+
node.children.text
52+
end
53+
end
54+
end
55+
end

‎lib/calendav/client.rb

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# frozen_string_literal: true
2+
3+
require_relative "./contextual_url"
4+
require_relative "./endpoint"
5+
require_relative "./clients/calendars_client"
6+
require_relative "./clients/events_client"
7+
require_relative "./requests/current_user_principal"
8+
9+
module Calendav
10+
class Client
11+
def initialize(credentials)
12+
@credentials = credentials
13+
end
14+
15+
def calendars
16+
@calendars = Clients::CalendarsClient.new(self, endpoint, credentials)
17+
end
18+
19+
def events
20+
@events = Clients::EventsClient.new(self, endpoint, credentials)
21+
end
22+
23+
def principal_url
24+
@principal_url ||= begin
25+
request = Requests::CurrentUserPrincipal.call
26+
27+
ContextualURL.call(
28+
credentials,
29+
endpoint
30+
.propfind(request.to_xml)
31+
.xpath(".//dav:current-user-principal/dav:href")
32+
.text
33+
)
34+
end
35+
end
36+
37+
private
38+
39+
attr_reader :credentials
40+
41+
def endpoint
42+
@endpoint ||= Endpoint.new(credentials)
43+
end
44+
end
45+
end
+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# frozen_string_literal: true
2+
3+
require "securerandom"
4+
5+
require_relative "../calendar"
6+
require_relative "../requests/calendar_home_set"
7+
require_relative "../requests/list_calendars"
8+
require_relative "../requests/make_calendar"
9+
10+
module Calendav
11+
module Clients
12+
class CalendarsClient
13+
def initialize(client, endpoint, credentials)
14+
@client = client
15+
@endpoint = endpoint
16+
@credentials = credentials
17+
end
18+
19+
def home_url
20+
@home_url ||= begin
21+
request = Requests::CalendarHomeSet.call
22+
23+
ContextualURL.call(
24+
credentials,
25+
endpoint
26+
.propfind(request.to_xml, url: client.principal_url)
27+
.xpath(".//caldav:calendar-home-set/dav:href")
28+
.text
29+
)
30+
end
31+
end
32+
33+
def create(attributes)
34+
request = Requests::MakeCalendar.call(attributes)
35+
36+
id = SecureRandom.uuid
37+
id = "/#{id}" unless home_url.end_with?("/")
38+
url = home_url + id
39+
40+
endpoint.mkcalendar(request.to_xml, url: url)
41+
42+
url
43+
end
44+
45+
def delete(url)
46+
endpoint.delete(url: url)
47+
end
48+
49+
def list
50+
request = Requests::ListCalendars.call
51+
calendar_xpath = ".//dav:resourcetype/caldav:calendar"
52+
53+
endpoint
54+
.propfind(request.to_xml, url: home_url, depth: 1)
55+
.xpath(".//dav:response")
56+
.select { |node| node.xpath(calendar_xpath).any? }
57+
.collect { |node| Calendar.from_xml(node) }
58+
end
59+
60+
private
61+
62+
attr_reader :client, :endpoint, :credentials
63+
end
64+
end
65+
end

‎lib/calendav/clients/events_client.rb

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# frozen_string_literal: true
2+
3+
require_relative "../event"
4+
require_relative "../requests/list_events"
5+
6+
module Calendav
7+
module Clients
8+
class EventsClient
9+
def initialize(client, endpoint, credentials)
10+
@client = client
11+
@endpoint = endpoint
12+
@credentials = credentials
13+
end
14+
15+
def create(calendar_url, event_identifier, ics)
16+
url = merged_url(calendar_url, event_identifier)
17+
result = endpoint.put(ics, url: url, content_type: :ics)
18+
19+
result.headers["Location"]
20+
end
21+
22+
def delete(event_url)
23+
endpoint.delete(url: event_url)
24+
end
25+
26+
def list(calendar_url, from:, to:)
27+
request = Requests::ListEvents.call(from: from, to: to)
28+
29+
endpoint
30+
.report(request.to_xml, url: calendar_url, depth: 1)
31+
.xpath(".//dav:response")
32+
.collect { |node| Event.from_xml(node) }
33+
end
34+
35+
private
36+
37+
attr_reader :client, :endpoint, :credentials
38+
39+
def merged_url(calendar_url, event_identifier)
40+
if calendar_url.end_with?("/")
41+
"#{calendar_url}#{event_identifier}"
42+
else
43+
"#{calendar_url}/#{event_identifier}"
44+
end
45+
end
46+
end
47+
end
48+
end

‎lib/calendav/contextual_url.rb

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# frozen_string_literal: true
2+
3+
module Calendav
4+
class ContextualURL
5+
def self.call(credentials, url_or_path)
6+
return credentials.host.to_s if url_or_path.nil? || url_or_path.empty?
7+
8+
if url_or_path.start_with?("/")
9+
credentials.host.dup.tap { |new_url| new_url.path = url_or_path }.to_s
10+
else
11+
URI(url_or_path).to_s
12+
end
13+
end
14+
end
15+
end

‎lib/calendav/credentials/apple.rb

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# frozen_string_literal: true
2+
3+
require "http"
4+
require "uri"
5+
6+
require_relative "./standard"
7+
8+
module Calendav
9+
module Credentials
10+
class Apple < Standard
11+
def initialize(username:, password:)
12+
super(
13+
host: "https://caldav.icloud.com",
14+
username: username,
15+
password: password
16+
)
17+
end
18+
end
19+
end
20+
end

‎lib/calendav/credentials/fastmail.rb

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# frozen_string_literal: true
2+
3+
require "http"
4+
require "uri"
5+
6+
require_relative "./standard"
7+
8+
module Calendav
9+
module Credentials
10+
class FastMail < Standard
11+
def initialize(username:, password:)
12+
super(
13+
host: "https://caldav.fastmail.com/dav/",
14+
username: username,
15+
password: password
16+
)
17+
end
18+
end
19+
end
20+
end

‎lib/calendav/credentials/google.rb

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# frozen_string_literal: true
2+
3+
require "http"
4+
require "uri"
5+
6+
require_relative "./standard"
7+
8+
module Calendav
9+
module Credentials
10+
class Google < Standard
11+
def initialize(username:, password:)
12+
super(
13+
host: "https://apidata.googleusercontent.com/caldav/v2/",
14+
username: username,
15+
password: password,
16+
authentication: :bearer_token
17+
)
18+
end
19+
end
20+
end
21+
end

‎lib/calendav/credentials/standard.rb

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# frozen_string_literal: true
2+
3+
require "uri"
4+
5+
module Calendav
6+
module Credentials
7+
class Standard
8+
attr_reader :host, :username, :password, :authentication
9+
10+
def initialize(host:, username:, password:, authentication: :basic_auth)
11+
@host = URI(host)
12+
@username = username
13+
@password = password
14+
@authentication = authentication
15+
end
16+
end
17+
end
18+
end

‎lib/calendav/endpoint.rb

+99
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
# frozen_string_literal: true
2+
3+
require_relative "./contextual_url"
4+
require_relative "./xml_processor"
5+
6+
module Calendav
7+
class Endpoint
8+
CONTENT_TYPES = {
9+
ics: "text/calendar",
10+
xml: "application/xml; charset=utf-8"
11+
}.freeze
12+
13+
RequestFailedError = Class.new(StandardError)
14+
15+
def initialize(credentials)
16+
@credentials = credentials
17+
end
18+
19+
def delete(url:)
20+
request(:delete, url: url).status.success?
21+
end
22+
23+
def mkcalendar(body, url:)
24+
request(
25+
:mkcalendar,
26+
body,
27+
url: url,
28+
http: with_headers(content_type: :xml)
29+
)
30+
end
31+
32+
def propfind(body, url: nil, depth: 0)
33+
request(
34+
:propfind,
35+
body,
36+
url: url,
37+
http: with_headers(depth: depth, content_type: :xml)
38+
)
39+
end
40+
41+
def put(body, url:, content_type: nil)
42+
request(
43+
:put,
44+
body,
45+
url: url,
46+
http: with_headers(content_type: content_type)
47+
)
48+
end
49+
50+
def report(body, url: nil, depth: 0)
51+
request(
52+
:report,
53+
body,
54+
url: url,
55+
http: with_headers(depth: depth, content_type: :xml)
56+
)
57+
end
58+
59+
private
60+
61+
attr_reader :credentials
62+
63+
def authenticated
64+
case credentials.authentication
65+
when :basic_auth
66+
HTTP.basic_auth(user: credentials.username, pass: credentials.password)
67+
when :bearer_token
68+
HTTP.auth("Bearer #{credentials.password}")
69+
else
70+
raise "Unexpected authentication approach: " \
71+
"#{credentials.authentication}"
72+
end
73+
end
74+
75+
def with_headers(content_type: nil, depth: nil)
76+
http = authenticated
77+
78+
http = http.headers(depth: depth) if depth
79+
if content_type
80+
http = http.headers("Content-Type" => CONTENT_TYPES[content_type])
81+
end
82+
83+
http
84+
end
85+
86+
def request(verb, body = nil, url:, http: with_headers)
87+
response = http.request(
88+
verb, ContextualURL.call(credentials, url), body: body
89+
)
90+
unless response.status.success?
91+
raise RequestFailedError, response.status.to_s
92+
end
93+
94+
return response if response.content_length&.zero?
95+
96+
XMLProcessor.call(response.body)
97+
end
98+
end
99+
end

‎lib/calendav/event.rb

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# frozen_string_literal: true
2+
3+
require_relative "./xml_processor"
4+
5+
module Calendav
6+
class Event
7+
attr_reader :path
8+
9+
def self.from_xml(node)
10+
new(
11+
node.xpath("./dav:href").text,
12+
node.xpath(".//dav:prop/*").to_xml,
13+
node.namespaces
14+
)
15+
end
16+
17+
def initialize(path, attribute_nodes, namespaces = {})
18+
@path = path
19+
@attribute_nodes = attribute_nodes
20+
@namespaces = namespaces
21+
end
22+
23+
def calendar_data
24+
attribute_value fragment.xpath("//caldav:calendar-data")
25+
end
26+
27+
def etag
28+
attribute_value fragment.xpath("//dav:getetag")
29+
end
30+
31+
def summary
32+
inner_event.summary
33+
end
34+
35+
private
36+
37+
attr_reader :attribute_nodes, :namespaces
38+
39+
def fragment
40+
@fragment ||= XMLProcessor.call(
41+
"<nodes>#{attribute_nodes}</nodes>", namespaces
42+
)
43+
end
44+
45+
def attribute_value(node)
46+
return nil if node.children.empty?
47+
48+
if node.children.any?(&:element?)
49+
node.children.select(&:element?).collect(&:to_xml).join
50+
else
51+
node.children.text
52+
end
53+
end
54+
55+
def inner_calendar
56+
Icalendar::Calendar.parse(calendar_data).first
57+
end
58+
59+
def inner_event
60+
@inner_event = inner_calendar.events.first
61+
end
62+
end
63+
end
+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# frozen_string_literal: true
2+
3+
require "nokogiri"
4+
5+
require_relative "../xml_processor"
6+
7+
module Calendav
8+
module Requests
9+
class CalendarHomeSet
10+
def self.call(...)
11+
new(...).call
12+
end
13+
14+
def call
15+
Nokogiri::XML::Builder.new do |xml|
16+
xml["dav"].propfind(XMLProcessor::NAMESPACES) do
17+
xml["dav"].prop do
18+
xml["caldav"].public_send(:"calendar-home-set")
19+
end
20+
end
21+
end
22+
end
23+
end
24+
end
25+
end
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# frozen_string_literal: true
2+
3+
require "nokogiri"
4+
5+
require_relative "../xml_processor"
6+
7+
module Calendav
8+
module Requests
9+
class CurrentUserPrincipal
10+
def self.call(...)
11+
new(...).call
12+
end
13+
14+
def call
15+
Nokogiri::XML::Builder.new do |xml|
16+
xml["dav"].propfind(XMLProcessor::NAMESPACES) do
17+
xml["dav"].prop do
18+
xml["dav"].public_send(:"current-user-principal")
19+
end
20+
end
21+
end
22+
end
23+
end
24+
end
25+
end
+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# frozen_string_literal: true
2+
3+
require "nokogiri"
4+
5+
require_relative "../xml_processor"
6+
7+
module Calendav
8+
module Requests
9+
class ListCalendars
10+
def self.call(...)
11+
new(...).call
12+
end
13+
14+
def call
15+
Nokogiri::XML::Builder.new do |xml|
16+
xml["dav"].propfind(XMLProcessor::NAMESPACES) do
17+
xml["dav"].prop do
18+
xml["dav"].displayname
19+
xml["dav"].resourcetype
20+
xml["dav"].getetag
21+
xml["cs"].getctag
22+
xml["apple"].public_send(:"calendar-color")
23+
end
24+
end
25+
end
26+
end
27+
end
28+
end
29+
end

‎lib/calendav/requests/list_events.rb

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# frozen_string_literal: true
2+
3+
require "nokogiri"
4+
5+
require_relative "../xml_processor"
6+
7+
module Calendav
8+
module Requests
9+
class ListEvents
10+
def self.call(...)
11+
new(...).call
12+
end
13+
14+
def initialize(from:, to:)
15+
@from = from
16+
@to = to
17+
end
18+
19+
def call
20+
Nokogiri::XML::Builder.new do |xml|
21+
xml["caldav"].public_send(
22+
"calendar-query", XMLProcessor::NAMESPACES
23+
) do
24+
xml["dav"].prop do
25+
xml["dav"].getetag
26+
xml["caldav"].public_send(:"calendar-data")
27+
end
28+
xml["caldav"].filter do
29+
xml["caldav"].public_send(:"comp-filter", name: "VCALENDAR") do
30+
xml["caldav"].public_send(:"comp-filter", name: "VEVENT") do
31+
xml["caldav"].public_send(
32+
:"time-range",
33+
start: from.utc.iso8601.delete(":-"),
34+
end: to.utc.iso8601.delete(":-")
35+
)
36+
end
37+
end
38+
end
39+
end
40+
end
41+
end
42+
43+
private
44+
45+
attr_reader :from, :to
46+
end
47+
end
48+
end
+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# frozen_string_literal: true
2+
3+
require "nokogiri"
4+
5+
require_relative "../xml_processor"
6+
7+
module Calendav
8+
module Requests
9+
class MakeCalendar
10+
def self.call(...)
11+
new(...).call
12+
end
13+
14+
def initialize(attributes)
15+
@attributes = attributes
16+
end
17+
18+
def call
19+
Nokogiri::XML::Builder.new do |xml|
20+
xml["caldav"].propfind(XMLProcessor::NAMESPACES) do
21+
xml["dav"].set do
22+
xml["dav"].prop do
23+
xml["dav"].displayname display_name
24+
25+
if description
26+
xml["caldav"].public_send(
27+
:"calendar-description", description
28+
)
29+
end
30+
31+
if time_zone
32+
xml["caldav"].public_send(:"calendar-timezone", time_zone)
33+
end
34+
35+
xml["caldav"].public_send(
36+
:"supported-calendar-component-set"
37+
) do
38+
xml["caldav"].comp name: "VEVENT"
39+
end
40+
end
41+
end
42+
end
43+
end
44+
end
45+
46+
private
47+
48+
attr_reader :attributes
49+
50+
def display_name
51+
attributes[:display_name]
52+
end
53+
54+
def description
55+
attributes[:description]
56+
end
57+
58+
def time_zone
59+
attributes[:time_zone]
60+
end
61+
end
62+
end
63+
end

‎lib/calendav/xml_processor.rb

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# frozen_string_literal: true
2+
3+
module Calendav
4+
class XMLProcessor
5+
NAMESPACES = {
6+
"xmlns:dav" => "DAV:",
7+
"xmlns:caldav" => "urn:ietf:params:xml:ns:caldav",
8+
"xmlns:cs" => "http://calendarserver.org/ns/",
9+
"xmlns:apple" => "http://apple.com/ns/ical/"
10+
}.freeze
11+
12+
def self.call(...)
13+
new(...).call
14+
end
15+
16+
def initialize(raw, namespaces = NAMESPACES)
17+
@raw = raw
18+
@namespaces = namespaces
19+
end
20+
21+
def call
22+
document = parse(raw)
23+
24+
namespaces.each do |key, value|
25+
document.root[key] = value unless document.namespaces[key]
26+
end
27+
28+
parse(document.to_xml)
29+
end
30+
31+
private
32+
33+
attr_reader :raw, :namespaces
34+
35+
def parse(string)
36+
Nokogiri::XML(string) { |config| config.strict.noblanks }
37+
rescue Nokogiri::XML::SyntaxError
38+
puts string
39+
raise
40+
end
41+
end
42+
end

‎spec/acceptance/google_spec.rb

+94
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
# frozen_string_literal: true
2+
3+
require "googleauth"
4+
require "icalendar"
5+
require "uri"
6+
7+
RSpec.describe "Google" do
8+
let(:provider) { :google }
9+
let(:username) { ENV.fetch("GOOGLE_USERNAME") }
10+
let(:access_token) { @access_token }
11+
let(:credentials) { Calendav.credentials(provider, username, access_token) }
12+
13+
subject { Calendav.client(credentials) }
14+
15+
before :context do
16+
@access_token = begin
17+
credentials = Google::Auth::UserRefreshCredentials.new(
18+
client_id: ENV.fetch("GOOGLE_CLIENT_ID"),
19+
scope: [],
20+
client_secret: ENV.fetch("GOOGLE_CLIENT_SECRET"),
21+
refresh_token: ENV.fetch("GOOGLE_REFRESH_TOKEN"),
22+
additional_parameters: { "access_type" => "offline" }
23+
)
24+
credentials.fetch_access_token!
25+
credentials.access_token
26+
end
27+
end
28+
29+
it "determines the user's principal URL" do
30+
expect(subject.principal_url)
31+
.to eq("https://apidata.googleusercontent.com/caldav/v2/#{URI.encode_www_form_component(username)}/user")
32+
end
33+
34+
it "determines the user's calendar URL" do
35+
expect(subject.calendars.home_url)
36+
.to eq("https://apidata.googleusercontent.com/caldav/v2/#{URI.encode_www_form_component(username)}/")
37+
end
38+
39+
it "can create and delete calendars" do
40+
skip "Not supported by Google"
41+
url = subject.calendars.create(
42+
display_name: "Calendav Test"
43+
)
44+
45+
subject.calendars.delete(url)
46+
end
47+
48+
it "can find calendars" do
49+
calendars = subject.calendars.list
50+
51+
expect(calendars.collect(&:display_name)).to include("Calendav Test")
52+
end
53+
54+
context "with a calendar" do
55+
let(:calendars) { subject.calendars.list }
56+
let(:calendar_url) do
57+
calendars.detect { |cal| cal.display_name == "Calendav Test" }&.path ||
58+
subject.calendars.create(display_name: "Calendav Test")
59+
end
60+
let(:identifier) { "#{SecureRandom.uuid}.ics" }
61+
let(:start) { Time.new 2021, 6, 1, 10, 30 }
62+
let(:finish) { Time.new 2021, 6, 1, 12, 30 }
63+
64+
after :each do
65+
next if calendars.detect { |cal| cal.display_name == "Calendav Test" }
66+
67+
subject.calendars.delete(calendar_url)
68+
end
69+
70+
it "can create, find and delete events" do
71+
ics = Icalendar::Calendar.new
72+
ics.event do |event|
73+
event.dtstart = start
74+
event.dtend = finish
75+
event.summary = "Brunch"
76+
end
77+
ics.publish
78+
79+
# Create an event
80+
event_url = subject.events.create(calendar_url, identifier, ics.to_ical)
81+
expect(event_url).to include(URI.decode_www_form_component(calendar_url))
82+
83+
# Search for the event
84+
events = subject.events.list(
85+
calendar_url, from: Time.new(2021, 6, 1), to: Time.new(2021, 6, 2)
86+
)
87+
expect(events.length).to eq(1)
88+
expect(events.first.summary).to eq("Brunch")
89+
90+
# Delete the event
91+
expect(subject.events.delete(event_url)).to eq(true)
92+
end
93+
end
94+
end

‎spec/spec_helper.rb

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# frozen_string_literal: true
2+
3+
require "calendav"
4+
require "dotenv"
5+
6+
Dotenv.load
7+
8+
RSpec.configure do |config|
9+
config.disable_monkey_patching!
10+
11+
config.expect_with :rspec do |c|
12+
c.syntax = :expect
13+
end
14+
end

0 commit comments

Comments
 (0)
Please sign in to comment.