Module: Async::Caldav::Handlers::Put

Defined in:
lib/async/caldav/handlers/put.rb

Class Method Summary collapse

Class Method Details

.call(path:, body:, storage:, headers: {}, resource_type: nil) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/async/caldav/handlers/put.rb', line 13

def call(path:, body:, storage:, headers: {}, resource_type: nil, **)
  return [400, { 'content-type' => 'text/plain' }, ['Empty body']] if body.nil? || body.strip.empty?

  # Validate body format
  if resource_type == :calendar
    return [400, { 'content-type' => 'text/plain' }, ['Invalid calendar data']] unless body.start_with?('BEGIN:VCALENDAR')
    content_type = headers['content-type'] || 'text/calendar'
  elsif resource_type == :addressbook
    return [400, { 'content-type' => 'text/plain' }, ['Invalid vCard data']] unless body.start_with?('BEGIN:VCARD')
    content_type = headers['content-type'] || 'text/vcard'
  else
    content_type = headers['content-type'] || 'application/octet-stream'
  end

  existing = storage.get_item(path.to_s)

  # Precondition checks
  if_match = headers['if-match']
  if_none_match = headers['if-none-match']

  if if_match && (!existing || existing[:etag] != if_match)
    return [412, { 'content-type' => 'text/plain' }, ['Precondition Failed']]
  end

  if if_none_match == '*' && existing
    return [412, { 'content-type' => 'text/plain' }, ['Precondition Failed']]
  end

  # UID conflict check for new items
  if !existing
    uid = extract_uid(body)
    if uid
      collection_path = path.parent.to_s
      items = storage.list_items(collection_path)
      items.each do |item_path, item_data|
        next if item_path == path.to_s
        if extract_uid(item_data[:body]) == uid
          return [409, { 'content-type' => 'text/plain' }, ['UID conflict']]
        end
      end
    end
  end

  item, is_new = storage.put_item(path.to_s, body, content_type)

  if is_new
    [201, { 'etag' => item[:etag], 'content-type' => 'text/plain' }, ['']]
  else
    [204, { 'etag' => item[:etag] }, ['']]
  end
end