]> git.openstreetmap.org Git - rails.git/blob - lib/potlatch.rb
Fix most auto-correctable rubocop issues
[rails.git] / lib / potlatch.rb
1 require 'stringio'
2
3 # The Potlatch module provides helper functions for potlatch and its communication with the server
4 module Potlatch
5   # The AMF class is a set of helper functions for encoding and decoding AMF.
6   class AMF
7     # Return two-byte integer
8     def self.getint(s)
9       s.getbyte * 256 + s.getbyte
10     end
11
12     # Return four-byte long
13     def self.getlong(s)
14       ((s.getbyte * 256 + s.getbyte) * 256 + s.getbyte) * 256 + s.getbyte
15     end
16
17     # Return string with two-byte length
18     def self.getstring(s)
19       len = s.getbyte * 256 + s.getbyte
20       str = s.read(len)
21       str.force_encoding("UTF-8") if str.respond_to?("force_encoding")
22       str
23     end
24
25     # Return eight-byte double-precision float
26     def self.getdouble(s)
27       a = s.read(8).unpack('G')                 # G big-endian, E little-endian
28       a[0]
29     end
30
31     # Return numeric array
32     def self.getarray(s)
33       len = getlong(s)
34       arr = []
35       for i in (0..len - 1)
36         arr[i] = getvalue(s)
37       end
38       arr
39     end
40
41     # Return object/hash
42     def self.getobject(s)
43       arr = {}
44       while (key = getstring(s))
45         if (key == '') then break end
46         arr[key] = getvalue(s)
47       end
48       s.getbyte         # skip the 9 'end of object' value
49       arr
50     end
51
52     # Parse and get value
53     def self.getvalue(s)
54       case s.getbyte
55       when 0 then       return getdouble(s)                     # number
56       when 1 then       return s.getbyte                        # boolean
57       when 2 then       return getstring(s)                     # string
58       when 3 then       return getobject(s)                     # object/hash
59       when 5 then       return nil                              # null
60       when 6 then       return nil                              # undefined
61       when 8 then       s.read(4)                               # mixedArray
62                   return getobject(s)                   #  |
63       when 10 then  return getarray(s)                  # array
64       else;     return nil                              # error
65       end
66     end
67
68     # Envelope data into AMF writeable form
69     def self.putdata(index, n)
70       d = encodestring(index + "/onResult")
71       d += encodestring("null")
72       d += [-1].pack("N")
73       d += encodevalue(n)
74     end
75
76     # Pack variables as AMF
77     def self.encodevalue(n)
78       case n.class.to_s
79       when 'Array'
80         a = 10.chr + encodelong(n.length)
81         n.each do |b|
82           a += encodevalue(b)
83         end
84         a
85       when 'Hash'
86         a = 3.chr
87         n.each do |k, v|
88           a += encodestring(k.to_s) + encodevalue(v)
89         end
90         a + 0.chr + 0.chr + 9.chr
91       when 'String'
92         2.chr + encodestring(n)
93       when 'Bignum', 'Fixnum', 'Float'
94         0.chr + encodedouble(n)
95       when 'NilClass'
96         5.chr
97     when 'TrueClass'
98       0.chr + encodedouble(1)
99     when 'FalseClass'
100       0.chr + encodedouble(0)
101     else
102       Rails.logger.error("Unexpected Ruby type for AMF conversion: " + n.class.to_s)
103       end
104     end
105
106     # Encode string with two-byte length
107     def self.encodestring(n)
108       n = n.dup.force_encoding("ASCII-8BIT") if n.respond_to?("force_encoding")
109       a, b = n.size.divmod(256)
110       a.chr + b.chr + n
111     end
112
113     # Encode number as eight-byte double precision float
114     def self.encodedouble(n)
115       [n].pack('G')
116     end
117
118     # Encode number as four-byte long
119     def self.encodelong(n)
120       [n].pack('N')
121     end
122   end
123
124   # The Dispatcher class handles decoding a series of RPC calls
125   # from the request, dispatching them, and encoding the response
126   class Dispatcher
127     def initialize(request, &_block)
128       # Get stream for request data
129       @request = StringIO.new(request + 0.chr)
130
131       # Skip version indicator and client ID
132       @request.read(2)
133
134       # Skip headers
135       AMF.getint(@request).times do     # Read number of headers and loop
136         AMF.getstring(@request)         #  | skip name
137         req.getbyte                     #  | skip boolean
138         AMF.getvalue(@request)          #  | skip value
139       end
140
141       # Capture the dispatch routine
142       @dispatch = Proc.new
143     end
144
145     def each(&_block)
146       # Read number of message bodies
147       bodies = AMF.getint(@request)
148
149       # Output response header
150       a, b = bodies.divmod(256)
151       yield 0.chr + 0.chr + 0.chr + 0.chr + a.chr + b.chr
152
153       # Process the bodies
154       bodies.times do                     # Read each body
155         name = AMF.getstring(@request)    #  | get message name
156         index = AMF.getstring(@request)   #  | get index in response sequence
157         bytes = AMF.getlong(@request)     #  | get total size in bytes
158         args = AMF.getvalue(@request)     #  | get response (probably an array)
159
160         result = @dispatch.call(name, *args)
161
162         yield AMF.putdata(index, result)
163       end
164     end
165   end
166
167   # The Potlatch class is a helper for Potlatch
168   class Potlatch
169     # ----- getpresets
170     #             in:   none
171     #             does: reads tag preset menus, colours, and autocomplete config files
172     #         out:  [0] presets, [1] presetmenus, [2] presetnames,
173     #                           [3] colours, [4] casing, [5] areas, [6] autotags
174     #                           (all hashes)
175     def self.get_presets
176       Rails.logger.info("  Message: getpresets")
177
178       # Read preset menus
179       presets = {}
180       presetmenus = {}; presetmenus['point'] = []; presetmenus['way'] = []; presetmenus['POI'] = []
181       presetnames = {}; presetnames['point'] = {}; presetnames['way'] = {}; presetnames['POI'] = {}
182       presettype = ''
183       presetcategory = ''
184       # StringIO.open(txt) do |file|
185       File.open("#{Rails.root}/config/potlatch/presets.txt") do |file|
186         file.each_line do|line|
187           t = line.chomp
188           if t =~ /(\w+)\/(\w+)/
189             presettype = $1
190             presetcategory = $2
191             presetmenus[presettype].push(presetcategory)
192             presetnames[presettype][presetcategory] = ["(no preset)"]
193           elsif t =~ /^([\w\s]+):\s?(.+)$/
194             pre = $1; kv = $2
195             presetnames[presettype][presetcategory].push(pre)
196             presets[pre] = {}
197             kv.split(',').each do|a|
198               if a =~ /^(.+)=(.*)$/ then presets[pre][$1] = $2 end
199             end
200           end
201         end
202       end
203
204       # Read colours/styling
205       colours = {}; casing = {}; areas = {}
206       File.open("#{Rails.root}/config/potlatch/colours.txt") do |file|
207         file.each_line do|line|
208           t = line.chomp
209           if t =~ /(\w+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)/
210             tag = $1
211             if ($2 != '-') then colours[tag] = $2.hex end
212             if ($3 != '-') then casing[tag] = $3.hex end
213             if ($4 != '-') then areas[tag] = $4.hex end
214           end
215         end
216       end
217
218       # Read relations colours/styling
219       relcolours = {}; relalphas = {}; relwidths = {}
220       File.open("#{Rails.root}/config/potlatch/relation_colours.txt") do |file|
221         file.each_line do|line|
222           t = line.chomp
223           if t =~ /(\w+)\s+([^\s]+)\s+([^\s]+)\s+([^\s]+)/
224             tag = $1
225             if ($2 != '-') then relcolours[tag] = $2.hex end
226             if ($3 != '-') then relalphas[tag] = $3.to_i end
227             if ($4 != '-') then relwidths[tag] = $4.to_i end
228           end
229         end
230       end
231
232       # Read POI presets
233       icon_list = []; icon_tags = {}
234       File.open("#{Rails.root}/config/potlatch/icon_presets.txt") do |file|
235         file.each_line do|line|
236           (icon, tags) = line.chomp.split("\t")
237           icon_list.push(icon)
238           icon_tags[icon] = Hash[*tags.scan(/([^;=]+)=([^;=]+)/).flatten]
239         end
240       end
241       icon_list.reverse!
242
243       # Read auto-complete
244       autotags = {}; autotags['point'] = {}; autotags['way'] = {}; autotags['POI'] = {}
245       File.open("#{Rails.root}/config/potlatch/autocomplete.txt") do |file|
246         file.each_line do|line|
247           t = line.chomp
248           if t =~ /^([\w:]+)\/(\w+)\s+(.+)$/
249             tag = $1; type = $2; values = $3
250             if values == '-' then autotags[type][tag] = []
251             else autotags[type][tag] = values.split(',').sort.reverse end
252           end
253         end
254       end
255
256       [presets, presetmenus, presetnames, colours, casing, areas, autotags, relcolours, relalphas, relwidths, icon_list, {}, icon_tags]
257     end
258   end
259 end