wms_base.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. """!
  2. @brief Preparation of parameters for drivers, which download it, and managing downloaded data.
  3. List of classes:
  4. - wms_base::WMSBase
  5. - wms_base::GRASSImporter
  6. - wms_base::WMSDriversInfo
  7. (C) 2012-2013 by the GRASS Development Team
  8. This program is free software under the GNU General Public License
  9. (>=v2). Read the file COPYING that comes with GRASS for details.
  10. @author Stepan Turek <stepan.turek seznam.cz> (Mentor: Martin Landa)
  11. """
  12. import os
  13. from math import ceil
  14. import base64
  15. try:
  16. from urllib2 import Request, urlopen, HTTPError
  17. from httplib import HTTPException
  18. except ImportError:
  19. from urllib.request import Request, urlopen
  20. from urllib.error import HTTPError
  21. from http.client import HTTPException
  22. import grass.script as grass
  23. from grass.exceptions import CalledModuleError
  24. class WMSBase:
  25. def __init__(self):
  26. # these variables are information for destructor
  27. self.temp_files_to_cleanup = []
  28. self.params = {}
  29. self.tile_size = {'bbox': None}
  30. self.temp_map = None
  31. self.temp_warpmap = None
  32. def __del__(self):
  33. # tries to remove temporary files, all files should be
  34. # removed before, implemented just in case of unexpected
  35. # stop of module
  36. for temp_file in self.temp_files_to_cleanup:
  37. grass.try_remove(temp_file)
  38. def _debug(self, fn, msg):
  39. grass.debug("%s.%s: %s" %
  40. (self.__class__.__name__, fn, msg))
  41. def _initializeParameters(self, options, flags):
  42. self._debug("_initialize_parameters", "started")
  43. # initialization of module parameters (options, flags)
  44. self.params['driver'] = options['driver']
  45. drv_info = WMSDriversInfo()
  46. driver_props = drv_info.GetDrvProperties(options['driver'])
  47. self._checkIgnoeredParams(options, flags, driver_props)
  48. self.params['capfile'] = options['capfile'].strip()
  49. for key in ['url', 'layers', 'styles', 'method']:
  50. self.params[key] = options[key].strip()
  51. self.flags = flags
  52. if self.flags['o']:
  53. self.params['transparent'] = 'FALSE'
  54. else:
  55. self.params['transparent'] = 'TRUE'
  56. for key in ['password', 'username', 'urlparams']:
  57. self.params[key] = options[key]
  58. if (self.params ['password'] and self.params ['username'] == '') or \
  59. (self.params['password'] == '' and self.params['username']):
  60. grass.fatal(_("Please insert both %s and %s parameters or none of them." %
  61. ('password', 'username')))
  62. self.params['bgcolor'] = options['bgcolor'].strip()
  63. if options['format'] == "jpeg" and \
  64. not 'format' in driver_props['ignored_params']:
  65. if not flags['o'] and \
  66. 'WMS' in self.params['driver']:
  67. grass.warning(_("JPEG format does not support transparency"))
  68. self.params['format'] = drv_info.GetFormat(options['format'])
  69. if not self.params['format']:
  70. self.params['format'] = self.params['format']
  71. # TODO: get srs from Tile Service file in OnEarth_GRASS driver
  72. self.params['srs'] = int(options['srs'])
  73. if self.params['srs'] <= 0 and not 'srs' in driver_props['ignored_params']:
  74. grass.fatal(_("Invalid EPSG code %d") % self.params['srs'])
  75. self.params['wms_version'] = options['wms_version']
  76. if "CRS" in GetSRSParamVal(self.params['srs']) and self.params['wms_version'] == "1.1.1":
  77. self.params['wms_version'] = "1.3.0"
  78. grass.warning(
  79. _("WMS version <1.3.0> will be used, because version <1.1.1> does not support <%s>projection") %
  80. GetSRSParamVal(
  81. self.params['srs']))
  82. if self.params['wms_version'] == "1.3.0":
  83. self.params['proj_name'] = "CRS"
  84. else:
  85. self.params['proj_name'] = "SRS"
  86. # read projection info
  87. self.proj_location = grass.read_command('g.proj',
  88. flags='jf').rstrip('\n')
  89. self.proj_location = self._modifyProj(self.proj_location)
  90. if self.params['srs'] in [3857, 900913]:
  91. # HACK: epsg 3857 def: http://spatialreference.org/ref/sr-org/7483/
  92. # g.proj can return: ...+a=6378137 +rf=298.257223563... (WGS84 elipsoid def instead of sphere), it can make 20km shift in Y, when raster is transformed
  93. # needed to be tested on more servers
  94. self.proj_srs = '+proj=merc +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +no_defs +a=6378137 +b=6378137 +nadgrids=@null +to_meter=1'
  95. else:
  96. self.proj_srs = grass.read_command('g.proj',
  97. flags='jf',
  98. epsg=str(GetEpsg(self.params['srs']))).rstrip('\n')
  99. self.proj_srs = self._modifyProj(self.proj_srs)
  100. if not self.proj_srs or not self.proj_location:
  101. grass.fatal(_("Unable to get projection info"))
  102. self.region = options['region']
  103. min_tile_size = 100
  104. maxcols = int(options['maxcols'])
  105. if maxcols <= min_tile_size:
  106. grass.fatal(_("Maxcols must be greater than 100"))
  107. maxrows = int(options['maxrows'])
  108. if maxrows <= min_tile_size:
  109. grass.fatal(_("Maxrows must be greater than 100"))
  110. # setting optimal tile size according to maxcols and maxrows constraint
  111. # and region cols and rows
  112. self.tile_size['cols'] = int(
  113. self.region['cols'] /
  114. ceil(
  115. self.region['cols'] /
  116. float(maxcols)))
  117. self.tile_size['rows'] = int(
  118. self.region['rows'] /
  119. ceil(
  120. self.region['rows'] /
  121. float(maxrows)))
  122. # default format for GDAL library
  123. self.gdal_drv_format = "GTiff"
  124. self._debug("_initialize_parameters", "finished")
  125. def _modifyProj(self, proj):
  126. """!Modify proj.4 string for usage in this module"""
  127. # add +wktext parameter to avoid droping of +nadgrids parameter (if presented) in gdalwarp
  128. if '+nadgrids=' in proj and ' +wktext' not in proj:
  129. proj += ' +wktext'
  130. return proj
  131. def _checkIgnoeredParams(self, options, flags, driver_props):
  132. """!Write warnings for set parameters and flags, which chosen driver does not use."""
  133. not_relevant_params = []
  134. for i_param in driver_props['ignored_params']:
  135. if i_param in options and \
  136. options[i_param] and \
  137. i_param not in ['srs', 'wms_version', 'format']: # params with default value
  138. not_relevant_params.append('<' + i_param + '>')
  139. if len(not_relevant_params) > 0:
  140. grass.warning(_("These parameter are ignored: %s\n\
  141. %s driver does not support the parameters." %
  142. (','.join(not_relevant_params), options['driver'])))
  143. not_relevant_flags = []
  144. for i_flag in driver_props['ignored_flags']:
  145. if flags[i_flag]:
  146. not_relevant_flags.append('<' + i_flag + '>')
  147. if len(not_relevant_flags) > 0:
  148. grass.warning(_("These flags are ignored: %s\n\
  149. %s driver does not support the flags." %
  150. (','.join(not_relevant_flags), options['driver'])))
  151. def GetMap(self, options, flags):
  152. """!Download data from WMS server."""
  153. self._initializeParameters(options, flags)
  154. self.bbox = self._computeBbox()
  155. self.temp_map = self._download()
  156. if not self.temp_map:
  157. return
  158. self._reprojectMap()
  159. return self.temp_warpmap
  160. def _fetchCapabilities(self, options):
  161. """!Download capabilities from WMS server
  162. """
  163. cap_url = options['url'].strip()
  164. if "?" in cap_url:
  165. cap_url += "&"
  166. else:
  167. cap_url += "?"
  168. if 'WMTS' in options['driver']:
  169. cap_url += "SERVICE=WMTS&REQUEST=GetCapabilities&VERSION=1.0.0"
  170. elif 'OnEarth' in options['driver']:
  171. cap_url += "REQUEST=GetTileService"
  172. else:
  173. cap_url += "SERVICE=WMS&REQUEST=GetCapabilities&VERSION=" + options['wms_version']
  174. if options['urlparams']:
  175. cap_url += "&" + options['urlparams']
  176. grass.debug('Fetching capabilities file.\n%s' % cap_url)
  177. try:
  178. cap = self._fetchDataFromServer(cap_url, options['username'], options['password'])
  179. except (IOError, HTTPException) as e:
  180. if isinstance(e, HTTPError) and e.code == 401:
  181. grass.fatal(
  182. _("Authorization failed to <%s> when fetching capabilities") %
  183. options['url'])
  184. else:
  185. msg = _("Unable to fetch capabilities from <%s>: %s") % (options['url'], e)
  186. if hasattr(e, 'reason'):
  187. msg += _("\nReason: ") + e.reason
  188. grass.fatal(msg)
  189. grass.debug('Fetching capabilities OK')
  190. return cap
  191. def _fetchDataFromServer(self, url, username=None, password=None):
  192. """!Fetch data from server
  193. """
  194. request = Request(url)
  195. if username and password:
  196. base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
  197. request.add_header("Authorization", "Basic %s" % base64string)
  198. try:
  199. return urlopen(request)
  200. except ValueError as error:
  201. grass.fatal("%s" % error)
  202. def GetCapabilities(self, options):
  203. """!Get capabilities from WMS server
  204. """
  205. cap = self._fetchCapabilities(options)
  206. capfile_output = options['capfile_output'].strip()
  207. # save to file
  208. if capfile_output:
  209. try:
  210. temp = open(capfile_output, "w")
  211. temp.write(cap.read())
  212. temp.close()
  213. return
  214. except IOError as error:
  215. grass.fatal(_("Unabble to open file '%s'.\n%s\n" % (cap_file, error)))
  216. # print to output
  217. cap_lines = cap.readlines()
  218. for line in cap_lines:
  219. print(line.rstrip())
  220. def _computeBbox(self):
  221. """!Get region extent for WMS query (bbox)
  222. """
  223. self._debug("_computeBbox", "started")
  224. bbox_region_items = {'maxy': 'n', 'miny': 's', 'maxx': 'e', 'minx': 'w'}
  225. bbox = {}
  226. if self.proj_srs == self.proj_location: # TODO: do it better
  227. for bbox_item, region_item in bbox_region_items.items():
  228. bbox[bbox_item] = self.region[region_item]
  229. # if location projection and wms query projection are
  230. # different, corner points of region are transformed into wms
  231. # projection and then bbox is created from extreme coordinates
  232. # of the transformed points
  233. else:
  234. for bbox_item, region_item in bbox_region_items.items():
  235. bbox[bbox_item] = None
  236. temp_region = self._tempfile()
  237. try:
  238. temp_region_opened = open(temp_region, 'w')
  239. temp_region_opened.write("%f %f\n%f %f\n%f %f\n%f %f\n" %
  240. (self.region['e'], self.region['n'],
  241. self.region['w'], self.region['n'],
  242. self.region['w'], self.region['s'],
  243. self.region['e'], self.region['s']))
  244. except IOError:
  245. grass.fatal(_("Unable to write data into tempfile"))
  246. finally:
  247. temp_region_opened.close()
  248. points = grass.read_command('m.proj', flags='d',
  249. proj_out=self.proj_srs,
  250. proj_in=self.proj_location,
  251. input=temp_region,
  252. quiet=True) # TODO: stdin
  253. grass.try_remove(temp_region)
  254. if not points:
  255. grass.fatal(_("Unable to determine region, %s failed") % 'm.proj')
  256. points = points.splitlines()
  257. if len(points) != 4:
  258. grass.fatal(_("Region definition: 4 points required"))
  259. for point in points:
  260. try:
  261. point = list(map(float, point.split("|")))
  262. except ValueError:
  263. grass.fatal(_('Reprojection of region using m.proj failed.'))
  264. if not bbox['maxy']:
  265. bbox['maxy'] = point[1]
  266. bbox['miny'] = point[1]
  267. bbox['maxx'] = point[0]
  268. bbox['minx'] = point[0]
  269. continue
  270. if bbox['maxy'] < point[1]:
  271. bbox['maxy'] = point[1]
  272. elif bbox['miny'] > point[1]:
  273. bbox['miny'] = point[1]
  274. if bbox['maxx'] < point[0]:
  275. bbox['maxx'] = point[0]
  276. elif bbox['minx'] > point[0]:
  277. bbox['minx'] = point[0]
  278. self._debug("_computeBbox", "finished -> %s" % bbox)
  279. # Ordering of coordinates axis of geographic coordinate
  280. # systems in WMS 1.3.0 is flipped. If self.tile_size['flip_coords'] is
  281. # True, coords in bbox need to be flipped in WMS query.
  282. return bbox
  283. def _reprojectMap(self):
  284. """!Reproject data using gdalwarp if needed
  285. """
  286. # reprojection of raster
  287. if self.proj_srs != self.proj_location: # TODO: do it better
  288. grass.message(_("Reprojecting raster..."))
  289. self.temp_warpmap = grass.tempfile()
  290. if int(os.getenv('GRASS_VERBOSE', '2')) <= 2:
  291. nuldev = file(os.devnull, 'w+')
  292. else:
  293. nuldev = None
  294. if self.params['method'] == "nearest":
  295. gdal_method = "near"
  296. elif self.params['method'] == "linear":
  297. gdal_method = "bilinear"
  298. else:
  299. gdal_method = self.params['method']
  300. #"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs"
  301. # RGB rasters - alpha layer is added for cropping edges of projected raster
  302. try:
  303. if self.temp_map_bands_num == 3:
  304. ps = grass.Popen(['gdalwarp',
  305. '-s_srs', '%s' % self.proj_srs,
  306. '-t_srs', '%s' % self.proj_location,
  307. '-r', gdal_method, '-dstalpha',
  308. self.temp_map, self.temp_warpmap], stdout=nuldev)
  309. # RGBA rasters
  310. else:
  311. ps = grass.Popen(['gdalwarp',
  312. '-s_srs', '%s' % self.proj_srs,
  313. '-t_srs', '%s' % self.proj_location,
  314. '-r', gdal_method,
  315. self.temp_map, self.temp_warpmap], stdout=nuldev)
  316. ps.wait()
  317. except OSError as e:
  318. grass.fatal('%s \nThis can be caused by missing %s utility. ' % (e, 'gdalwarp'))
  319. if nuldev:
  320. nuldev.close()
  321. if ps.returncode != 0:
  322. grass.fatal(_('%s failed') % 'gdalwarp')
  323. grass.try_remove(self.temp_map)
  324. # raster projection is same as projection of location
  325. else:
  326. self.temp_warpmap = self.temp_map
  327. self.temp_files_to_cleanup.remove(self.temp_map)
  328. return self.temp_warpmap
  329. def _tempfile(self):
  330. """!Create temp_file and append list self.temp_files_to_cleanup
  331. with path of file
  332. @return string path to temp_file
  333. """
  334. temp_file = grass.tempfile()
  335. if temp_file is None:
  336. grass.fatal(_("Unable to create temporary files"))
  337. # list of created tempfiles for destructor
  338. self.temp_files_to_cleanup.append(temp_file)
  339. return temp_file
  340. class GRASSImporter:
  341. def __init__(self, opt_output):
  342. self.cleanup_mask = False
  343. self.cleanup_layers = False
  344. # output map name
  345. self.opt_output = opt_output
  346. # suffix for existing mask (during overriding will be saved
  347. # into raster named:self.opt_output + this suffix)
  348. self.original_mask_suffix = "_temp_MASK"
  349. # check names of temporary rasters, which module may create
  350. maps = []
  351. for suffix in ('.red', '.green', '.blue', '.alpha', self.original_mask_suffix):
  352. rast = self.opt_output + suffix
  353. if grass.find_file(rast, element='cell', mapset='.')['file']:
  354. maps.append(rast)
  355. if len(maps) != 0:
  356. grass.fatal(_("Please change output name, or change names of these rasters: %s, "
  357. "module needs to create this temporary maps during execution.") % ",".join(maps))
  358. def __del__(self):
  359. # removes temporary mask, used for import transparent or warped temp_map
  360. if self.cleanup_mask:
  361. # clear temporary mask, which was set by module
  362. try:
  363. grass.run_command('r.mask', quiet=True, flags='r')
  364. except CalledModuleError:
  365. grass.fatal(_('%s failed') % 'r.mask')
  366. # restore original mask, if exists
  367. if grass.find_file(self.opt_output + self.original_mask_suffix,
  368. element='cell', mapset='.')['name']:
  369. try:
  370. mask_copy = self.opt_output + self.original_mask_suffix
  371. grass.run_command('g.copy', quiet=True,
  372. raster=mask_copy + ',MASK')
  373. except CalledModuleError:
  374. grass.fatal(_('%s failed') % 'g.copy')
  375. # remove temporary created rasters
  376. if self.cleanup_layers:
  377. maps = []
  378. for suffix in ('.red', '.green', '.blue', '.alpha', self.original_mask_suffix):
  379. rast = self.opt_output + suffix
  380. if grass.find_file(rast, element='cell', mapset='.')['file']:
  381. maps.append(rast)
  382. if maps:
  383. grass.run_command('g.remove',
  384. quiet=True,
  385. flags='fb',
  386. type='raster',
  387. name=','.join(maps))
  388. # delete environmental variable which overrides region
  389. if 'GRASS_REGION' in os.environ.keys():
  390. os.environ.pop('GRASS_REGION')
  391. def ImportMapIntoGRASS(self, raster):
  392. """!Import raster into GRASS.
  393. """
  394. # importing temp_map into GRASS
  395. try:
  396. grass.run_command('r.in.gdal',
  397. quiet=True, overwrite=True,
  398. input=raster, output=self.opt_output)
  399. except CalledModuleError:
  400. grass.fatal(_('%s failed') % 'r.in.gdal')
  401. # information for destructor to cleanup temp_layers, created
  402. # with r.in.gdal
  403. self.cleanup_layers = True
  404. # setting region for full extend of imported raster
  405. if grass.find_file(self.opt_output + '.red', element='cell', mapset='.')['file']:
  406. region_map = self.opt_output + '.red'
  407. else:
  408. region_map = self.opt_output
  409. os.environ['GRASS_REGION'] = grass.region_env(rast=region_map)
  410. # mask created from alpha layer, which describes real extend
  411. # of warped layer (may not be a rectangle), also mask contains
  412. # transparent parts of raster
  413. if grass.find_file(self.opt_output + '.alpha', element='cell', mapset='.')['name']:
  414. # saving current mask (if exists) into temp raster
  415. if grass.find_file('MASK', element='cell', mapset='.')['name']:
  416. try:
  417. mask_copy = self.opt_output + self.original_mask_suffix
  418. grass.run_command('g.copy', quiet=True,
  419. raster='MASK,' + mask_copy)
  420. except CalledModuleError:
  421. grass.fatal(_('%s failed') % 'g.copy')
  422. # info for destructor
  423. self.cleanup_mask = True
  424. try:
  425. grass.run_command('r.mask',
  426. quiet=True, overwrite=True,
  427. maskcats="0",
  428. flags='i',
  429. raster=self.opt_output + '.alpha')
  430. except CalledModuleError:
  431. grass.fatal(_('%s failed') % 'r.mask')
  432. # TODO one band + alpha band?
  433. if grass.find_file(self.opt_output + '.red', element='cell', mapset='.')['file']:
  434. try:
  435. grass.run_command('r.composite',
  436. quiet=True, overwrite=True,
  437. red=self.opt_output + '.red',
  438. green=self.opt_output + '.green',
  439. blue=self.opt_output + '.blue',
  440. output=self.opt_output)
  441. except CalledModuleError:
  442. grass.fatal(_('%s failed') % 'r.composite')
  443. grass.message(_('<%s> created.') % self.opt_output)
  444. class WMSDriversInfo:
  445. def __init__(self):
  446. """!Provides information about driver parameters.
  447. """
  448. # format labels
  449. self.f_labels = ["geotiff", "tiff", "png", "jpeg", "gif", "png8"]
  450. # form for request
  451. self.formats = [
  452. "image/geotiff",
  453. "image/tiff",
  454. "image/png",
  455. "image/jpeg",
  456. "image/gif",
  457. "image/png8"]
  458. self.srs = ("epsg", "crs")
  459. def GetDrvProperties(self, driver):
  460. """!Get information about driver parameters.
  461. """
  462. if driver == 'WMS_GDAL':
  463. return self._GDALDrvProperties()
  464. if 'WMS' in driver:
  465. return self._WMSProperties()
  466. if 'WMTS' in driver:
  467. return self._WMTSProperties()
  468. if 'OnEarth' in driver:
  469. return self._OnEarthProperties()
  470. def _OnEarthProperties(self):
  471. props = {}
  472. props['ignored_flags'] = ['o']
  473. props['ignored_params'] = ['bgcolor', 'styles', 'capfile_output',
  474. 'format', 'srs', 'wms_version']
  475. props['req_multiple_layers'] = False
  476. return props
  477. def _WMSProperties(self):
  478. props = {}
  479. props['ignored_params'] = ['capfile']
  480. props['ignored_flags'] = []
  481. props['req_multiple_layers'] = True
  482. return props
  483. def _WMTSProperties(self):
  484. props = {}
  485. props['ignored_flags'] = ['o']
  486. props['ignored_params'] = ['urlparams', 'bgcolor', 'wms_version']
  487. props['req_multiple_layers'] = False
  488. return props
  489. def _GDALDrvProperties(self):
  490. props = {}
  491. props['ignored_flags'] = []
  492. props['ignored_params'] = ['urlparams', 'bgcolor', 'capfile', 'capfile_output',
  493. 'username', 'password']
  494. props['req_multiple_layers'] = True
  495. return props
  496. def GetFormatLabel(self, format):
  497. """!Convert format request form to value in parameter 'format'.
  498. """
  499. if format in self.formats:
  500. return self.f_labels[self.formats.index(format)]
  501. return None
  502. def GetFormat(self, label):
  503. """!Convert value in parameter 'format' to format request form.
  504. """
  505. if label in self.f_labels:
  506. return self.formats[self.f_labels.index(label)]
  507. return None
  508. def GetSrs(self):
  509. """!Get supported srs prefixes (e.g. epsg/crs)
  510. @todo filter according to version and driver params
  511. """
  512. return self.srs
  513. # TODO move to utils?
  514. def GetSRSParamVal(srs):
  515. """!Decides whether to use CRS or EPSG prefix according to srs number.
  516. """
  517. if srs in [84, 83, 27]:
  518. return "CRS:%d" % srs
  519. else:
  520. return "EPSG:%d" % srs
  521. def GetEpsg(srs):
  522. """
  523. @return EPSG number
  524. If srs is CRS number, return EPSG number which corresponds to CRS number.
  525. """
  526. if srs == 84:
  527. return 4326
  528. if srs == 83:
  529. return 4269
  530. if srs == 27:
  531. return 4267
  532. return srs