Class: MrMurano::Webservice::Endpoint

Inherits:
WebserviceBase show all
Defined in:
lib/MrMurano/Webservice-Endpoint.rb

Defined Under Namespace

Classes: RouteItem

Constant Summary

Constants included from Verbose

Verbose::TABULARIZE_DATA_FORMAT_ERROR

Constants included from SolutionId

SolutionId::INVALID_API_ID, SolutionId::UNEXPECTED_TYPE_OR_ERROR_MSG

Constants included from AccountBase

AccountBase::LOGIN_ADVICE, AccountBase::LOGIN_NOTICE

Instance Attribute Summary

Attributes included from SolutionId

#api_id, #sid, #valid_api_id

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from WebserviceBase

#endpoint

Methods included from SyncUpDown

#config_vars_decode, #config_vars_encode, #debug_print_localitems, #diff_download, #diff_item_write, #download, #ignore?, #ignoring, #localitems, #locallist, #locallist_add_item, #locallist_complain_missing, #locallist_mark_seen, #location, #remove_or_clear, #removelocal, #resolve_config_var_usage!, #resurrect_undeletables, #searchFor, #syncdown_after, #syncdown_before, #syncup_after, #syncup_before, #tolocalpath, #update_mtime

Methods included from Verbose

ask_yes_no, #ask_yes_no, #assert, assert, cmd_confirm_delete!, #cmd_confirm_delete!, debug, #debug, dump_file_json, dump_file_plain, dump_file_yaml, #dump_output_file, #error, error, #error_file_format!, fancy_ticks, #fancy_ticks, #load_file_json, #load_file_plain, #load_file_yaml, #load_input_file, outf, #outf, #outformat_engine, #pluralize?, pluralize?, #prepare_hash_csv, #read_hashf!, #tabularize, tabularize, verbose, #verbose, warning, #warning, #whirly_interject, whirly_interject, #whirly_linger, whirly_linger, #whirly_msg, whirly_msg, #whirly_pause, whirly_pause, #whirly_start, whirly_start, #whirly_stop, whirly_stop, #whirly_unpause, whirly_unpause

Methods included from SyncCore

#debug_selected, #dodiff, #dodiff_build_cmd, #dodiff_cull_tempfile_paths, #dodiff_do_diff, #dodiff_download_remote, #dodiff_flexible, #dodiff_header_aware, #dodiff_local_to_tempfile, #dodiff_prepare_local_and_diff, #dodiff_resolve_localname, #dodiff_tempfile_paths, #filter_solution, #init_mods_and_chgs_arrs, #item_dirty_set_status, #item_local_there_merged, #item_merged_diff_status, #item_merged_set_status, #item_select_selected!, #items_classify_and_find_duplicates, #items_cull_clashes!, #items_lists, #items_log_duplicates, #items_log_duplicates_there_local, #items_mods_and_chgs!, #items_new_and_old!, #select_selected!, #sort_by_name, #status, #sync_update_progress, #syncable_validate_api_id, #syncdown, #syncdown_item, #syncup, #syncup_item

Methods included from SyncAllowed

#download_item_allowed, #remove_item_allowed, #removelocal_item_allowed, #sync_item_allowed, #upload_item_allowed

Methods included from SolutionId

#affirm_valid, #api_id?, #endpoint, #init_api_id!, #valid_api_id?

Methods included from AccountBase

#add_headers, #ask_for_password!, #ask_for_user!, #cfg_clear_user_and_business, #credentials_reset, #get, #invalidate_token, #login_info, #logout, #must_prompt_if_logged_off!, #token, #token_reset, #verify_cfg_auth!, #verify_cfg_auth_persist, #verify_cfg_auth_scheme!, #verify_cfg_auth_ttl, #verify_set, warn_configfile_env_maybe

Methods included from Http

#add_headers, #curldebug, curldebug_after, curldebug_elapsed, curldebug_log, #delete, #endpoint, #get, #host, #http, #http_reset, #isJSON, #json_opts, #patch, #post, #postf, #put, #showHttpError, #user, #workit, #workit_response

Constructor Details

#initializeEndpoint



38
39
40
41
42
43
# File 'lib/MrMurano/Webservice-Endpoint.rb', line 38

def initialize
  super
  @uriparts << :endpoint
  @project_section = :routes
  @match_header = /--#ENDPOINT (?<method>\S+) (?<path>\S+)( (?<ctype>.*))?/
end

Class Method Details

.descriptionObject



45
46
47
48
49
50
# File 'lib/MrMurano/Webservice-Endpoint.rb', line 45

def self.description
  # 2017-08-07: UI and ProjectFile call these "Routes". Let's be consistent.
  # 2017-08-14: UI team says "Route" changing to "Endpoint" in new UI.
  #%(Route)
  %(Endpoint)
end

Instance Method Details

#docmp(item_a, item_b) ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/MrMurano/Webservice-Endpoint.rb', line 235

def docmp(item_a, item_b)
  if item_a[:script].nil? && item_a[:local_path]
    item_a[:script] = item_a[:local_path].read
  end
  if item_b[:script].nil? && item_b[:local_path]
    item_b[:script] = item_b[:local_path].read
  end
  cmp = false
  cmp ||= item_a[:content_type] != item_b[:content_type]
  cmp ||= item_a[:script] != item_b[:script]
  cmp
end

#fetch(id, untainted = false) ⇒ Object



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/MrMurano/Webservice-Endpoint.rb', line 69

def fetch(id, untainted=false)
  ret = get('/' + id.to_s)
  unless ret.is_a?(Hash) && !ret.key?(:error)
    error "#{UNEXPECTED_TYPE_OR_ERROR_MSG}: #{ret}"
    ret = {}
  end

  ret[:content_type] = 'application/json' if ret[:content_type].empty?

  if untainted
    script = ret[:script]
  else
    add_terminating_nl = ret[:script].end_with? "\n"
    script = ret[:script].lines.map(&:chomp)
    fetch_fix_script_header(script, ret)
    script = script.join("\n")
    script += "\n" if add_terminating_nl
  end

  if block_given?
    yield script
  else
    script
  end
end

#fetch_fix_script_header(script, ret) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/MrMurano/Webservice-Endpoint.rb', line 95

def fetch_fix_script_header(script, ret)
  aheader = (script.first || '')

  rh = ['--#ENDPOINT', ret[:method].upcase, ret[:path]]
  rh << ret[:content_type] if ret[:content_type] != 'application/json'
  rheader = rh.join(' ')

  # If header is missing add it.
  # If header is wrong, replace it.
  md = @match_header.match(aheader)
  if md.nil?
    # header missing.
    script.unshift rheader
  elsif (
    md[:method] != ret[:method] ||
    md[:path] != ret[:path] ||
    md[:ctype] != ret[:content_type]
  )
    # header is wrong.
    script[0] = rheader
  end
  # otherwise current header is good.

  script
end

#listObject

This gets all data about all endpoints.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/MrMurano/Webservice-Endpoint.rb', line 54

def list
  ret = get
  return [] unless ret.is_a?(Array)
  ret.map do |item|
    if item[:content_type].to_s.empty?
      item[:content_type] = 'application/json'
    end
    # XXX should this update the script header?
    RouteItem.new(item)
  end
  # MAYBE/2017-08-17:
  #   ret.map! ...
  #   sort_by_name(ret)
end

#match(item, pattern) ⇒ Object



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/MrMurano/Webservice-Endpoint.rb', line 215

def match(item, pattern)
  # Pattern is: #{method}#{path glob}
  pattern_pattern = /^#(?<method>[^#]*)#(?<path>.*)/i
  md = pattern_pattern.match(pattern)
  return false if md.nil?
  debug "match pattern: '#{md[:method]}' '#{md[:path]}'"

  unless md[:method].empty?
    return false unless item[:method].casecmp(md[:method]).zero?
  end

  return true if md[:path].empty?

  ::File.fnmatch(md[:path], item[:path])
end

#remove(id) ⇒ Object

Delete an endpoint



162
163
164
165
# File 'lib/MrMurano/Webservice-Endpoint.rb', line 162

def remove(id)
  return unless remove_item_allowed(id)
  delete('/' + id.to_s)
end

#synckey(item) ⇒ Object



231
232
233
# File 'lib/MrMurano/Webservice-Endpoint.rb', line 231

def synckey(item)
  "#{item[:method].upcase}_#{item[:path]}"
end

#to_remote_items(_from, path) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/MrMurano/Webservice-Endpoint.rb', line 179

def to_remote_items(_from, path)
  # Path could be have multiple endpoints in side, so a loop.
  path = Pathname.new(path) unless path.is_a? Pathname
  items = []
  cur = nil
  lineno = 0
  path.readlines.each do |line|
    lineno += 1
    md = @match_header.match(line)
    if !md.nil?
      # header line.
      cur[:line_end] = lineno - 1 unless cur.nil?
      items << cur unless cur.nil?
      script_header = "--#ENDPOINT #{md[:method].upcase} #{md[:path]}"
      script_header += " #{md[:ctype]}" unless md[:ctype].to_s.empty?
      cur = RouteItem.new(
        method: md[:method].upcase,
        path: md[:path],
        content_type: (md[:ctype] || 'application/json'),
        local_path: path,
        line_beg: lineno,
        header: script_header,
        script: '',
      )
    elsif !cur.nil? && !cur[:script].nil?
      # 2017-07-02: Frozen string literal: change << to +=
      cur[:script] += line
    end
  end
  unless cur.nil?
    cur[:line_end] = lineno
    items << cur
  end
  items
end

#tolocalname(item, _key) ⇒ Object



167
168
169
170
171
172
173
174
175
176
177
# File 'lib/MrMurano/Webservice-Endpoint.rb', line 167

def tolocalname(item, _key)
  name = ''
  # 2017-07-02: Changing shovel operator << to +=
  # to support Ruby 3.0 frozen string literals.
  name += item[:path].split('/').reject(&:empty?).join('-')
  name += '.'
  # This downcase is just for the filename.
  name += item[:method].downcase
  name += '.lua'
  name
end

#upload(local, remote, _modify) ⇒ Object

Upload endpoint



126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/MrMurano/Webservice-Endpoint.rb', line 126

def upload(local, remote, _modify)
  local = Pathname.new(local) unless local.is_a? Pathname
  # MAYBE/2017-09-07: Honor options.ignore_errors here?
  raise 'no file' unless local.exist?
  # we assume these are small enough to slurp.
  if remote.script.nil?
    script = local.read
    remote[:script] = script
  end
  limitkeys = [:method, :path, :script, :content_type, @itemkey]
  itemkey = remote[@itemkey]
  remote = remote.reject_ephemeral.to_h.select { |k, _v| limitkeys.include? k }
  if !itemkey.nil?
    return unless upload_item_allowed(itemkey)
    put('/' + itemkey, remote) do |request, http|
      response = http.request(request)
      case response
      when Net::HTTPSuccess
        #return JSON.parse(response.body)
        return
      when Net::HTTPNotFound
        verbose "\tDoesn't exist, creating"
        post('/', remote)
      else
        showHttpError(request, response)
      end
    end
  else
    verbose "\tNo itemkey, creating"
    return unless upload_item_allowed(local)
    post('', remote)
  end
end