calendav 0.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
+ SHA256:
3
+ metadata.gz: 3afd38354db59046e38adcad9be4376d7354b4acf4f97205bcbdc313d0bf1706
4
+ data.tar.gz: 3642fbb9d38108adcdf5af63c41e4f01c846b86a1a36225e8fd9bd92b58ae088
5
+ SHA512:
6
+ metadata.gz: c54490f1ae94b3fb42c273777ccc29c342273bf8585b8270842e3402d383301867ec750eb2a0aaa3e51f770ef7f53a1094c4427e2e65de75fa3ba489eaa91667
7
+ data.tar.gz: 5e1855a5fde3e0adf27afbe387224617ffea0163eb82c6325320e2905a4bf176ff803cd8d6500da097a4001f35657e2be1144f8abbf9cfdca413d05267920f60
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -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.
data/Gemfile ADDED
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ gemspec
data/LICENSE.md ADDED
@@ -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.
data/README.md ADDED
@@ -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).
data/Rakefile ADDED
@@ -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]
data/lib/calendav.rb ADDED
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
metadata ADDED
@@ -0,0 +1,189 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: calendav
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Pat Allan
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-06-13 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: http
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: nokogiri
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: dotenv
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: googleauth
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: icalendar
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rake
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: rspec
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ - !ruby/object:Gem::Dependency
112
+ name: rubocop
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: '0'
125
+ description:
126
+ email:
127
+ - pat@freelancing-gods.com
128
+ executables: []
129
+ extensions: []
130
+ extra_rdoc_files: []
131
+ files:
132
+ - ".rspec"
133
+ - CHANGELOG.md
134
+ - Gemfile
135
+ - LICENSE.md
136
+ - README.md
137
+ - Rakefile
138
+ - lib/calendav.rb
139
+ - lib/calendav/calendar.rb
140
+ - lib/calendav/client.rb
141
+ - lib/calendav/clients/calendars_client.rb
142
+ - lib/calendav/clients/events_client.rb
143
+ - lib/calendav/contextual_url.rb
144
+ - lib/calendav/credentials/apple.rb
145
+ - lib/calendav/credentials/fastmail.rb
146
+ - lib/calendav/credentials/google.rb
147
+ - lib/calendav/credentials/standard.rb
148
+ - lib/calendav/endpoint.rb
149
+ - lib/calendav/event.rb
150
+ - lib/calendav/requests/calendar_home_set.rb
151
+ - lib/calendav/requests/current_user_principal.rb
152
+ - lib/calendav/requests/list_calendars.rb
153
+ - lib/calendav/requests/list_events.rb
154
+ - lib/calendav/requests/make_calendar.rb
155
+ - lib/calendav/xml_processor.rb
156
+ - spec/acceptance/google_spec.rb
157
+ - spec/spec_helper.rb
158
+ homepage: https://github.com/pat/calendav
159
+ licenses:
160
+ - Hippocratic-2.1
161
+ metadata:
162
+ homepage_uri: https://github.com/pat/calendav
163
+ source_code_uri: https://github.com/pat/calendav
164
+ changelog_uri: https://github.com/pat/calendav/blob/main/CHANGELOG.md
165
+ post_install_message:
166
+ rdoc_options: []
167
+ require_paths:
168
+ - lib
169
+ required_ruby_version: !ruby/object:Gem::Requirement
170
+ requirements:
171
+ - - ">="
172
+ - !ruby/object:Gem::Version
173
+ version: 2.7.0
174
+ required_rubygems_version: !ruby/object:Gem::Requirement
175
+ requirements:
176
+ - - ">="
177
+ - !ruby/object:Gem::Version
178
+ version: '0'
179
+ requirements: []
180
+ rubygems_version: 3.2.15
181
+ signing_key:
182
+ specification_version: 4
183
+ summary: CalDAV client
184
+ test_files:
185
+ - spec/acceptance/google_spec.rb
186
+ - spec/spec_helper.rb
187
+ - ".rspec"
188
+ - Gemfile
189
+ - Rakefile