locdownload.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. """
  2. @package startup.locdownload
  3. @brief GRASS Location Download Management
  4. Classes:
  5. - LocationDownloadPanel
  6. - LocationDownloadDialog
  7. - DownloadError
  8. (C) 2017 by Vaclav Petras the GRASS Development Team
  9. This program is free software under the GNU General Public License
  10. (>=v2). Read the file COPYING that comes with GRASS for details.
  11. @author Vaclav Petras <wenzeslaus gmail com>
  12. """
  13. from __future__ import print_function
  14. import os
  15. import sys
  16. import tempfile
  17. import shutil
  18. import textwrap
  19. import time
  20. try:
  21. from urllib2 import HTTPError, URLError
  22. from urllib import request, urlopen, urlretrieve
  23. except ImportError:
  24. # there is also HTTPException, perhaps change to list
  25. from urllib.error import HTTPError, URLError
  26. from urllib.request import urlopen, urlretrieve
  27. from urllib import request
  28. import wx
  29. from wx.lib.newevent import NewEvent
  30. from grass.script import debug
  31. from grass.script.utils import try_rmdir
  32. from grass.script.setup import set_gui_path
  33. set_gui_path()
  34. from core.debug import Debug
  35. from core.gthread import gThread
  36. from gui_core.wrap import Button, StaticText
  37. # TODO: labels (and descriptions) translatable?
  38. LOCATIONS = [
  39. {
  40. "label": "Complete NC location",
  41. "url": "https://grass.osgeo.org/sampledata/north_carolina/nc_spm_08_grass7.tar.gz",
  42. },
  43. {
  44. "label": "Basic NC location",
  45. "url": "https://grass.osgeo.org/sampledata/north_carolina/nc_basic_spm_grass7.tar.gz",
  46. },
  47. {
  48. "label": "World location in LatLong/WGS84",
  49. "url": "https://grass.osgeo.org/sampledata/worldlocation.tar.gz",
  50. },
  51. {
  52. "label": "Spearfish (SD) location",
  53. "url": "https://grass.osgeo.org/sampledata/spearfish_grass70data-0.3.tar.gz",
  54. },
  55. {
  56. "label": "Piemonte, Italy data set",
  57. "url": "http://geodati.fmach.it/gfoss_geodata/libro_gfoss/grassdata_piemonte_utm32n_wgs84_grass7.tar.gz",
  58. },
  59. {
  60. "label": "Slovakia 3D precipitation voxel data set",
  61. "url": "https://grass.osgeo.org/uploads/grass/sampledata/slovakia3d_grass7.tar.gz",
  62. },
  63. {
  64. "label": "Fire simulation sample data",
  65. "url": "https://grass.osgeo.org/sampledata/fire_grass6data.tar.gz",
  66. },
  67. {
  68. "label": "GISMentors location, Czech Republic",
  69. "url": "http://training.gismentors.eu/geodata/grass/gismentors.zip",
  70. },
  71. {
  72. "label": "Natural Earth Dataset in WGS84",
  73. "url": "https://github.com/baharmon/natural-earth-dataset/archive/natural-earth.zip",
  74. "size": "207 MB",
  75. "epsg": "4326",
  76. "license": "ODC Public Domain Dedication and License 1.0",
  77. "maintainer": "Brendan Harmon (brendan.harmon@gmail.com)",
  78. },
  79. ]
  80. class DownloadError(Exception):
  81. """Error happened during download or when processing the file"""
  82. pass
  83. class RedirectText(object):
  84. def __init__(self, window):
  85. self.out = window
  86. def write(self, string):
  87. try:
  88. if self.out:
  89. string = self._wrap_string(string)
  90. heigth = self._get_heigth(string)
  91. wx.CallAfter(self.out.SetLabel, string)
  92. self._resize(heigth)
  93. except:
  94. # window closed -> PyDeadObjectError
  95. pass
  96. def flush(self):
  97. pass
  98. def _wrap_string(self, string, width=40):
  99. """Wrap string
  100. :param str string: input string
  101. :param int width: maximum length allowed of the wrapped lines
  102. :return str: newline-separated string
  103. """
  104. wrapper = textwrap.TextWrapper(width=width)
  105. return wrapper.fill(text=string)
  106. def _get_heigth(self, string):
  107. """Get widget new heigth
  108. :param str string: input string
  109. :return int: widget heigth
  110. """
  111. n_lines = string.count('\n')
  112. attr = self.out.GetClassDefaultAttributes()
  113. font_size = attr.font.GetPointSize()
  114. heigth = int((n_lines + 2) * font_size // 0.75) # 1 px = 0.75 pt
  115. return heigth
  116. def _resize(self, heigth=-1):
  117. """Resize widget heigth
  118. :param int heigth: widget heigth
  119. """
  120. wx.CallAfter(self.out.GetParent().SetMinSize, (-1, -1))
  121. wx.CallAfter(self.out.SetMinSize, (-1, heigth))
  122. wx.CallAfter(
  123. self.out.GetParent().parent.sizer.Fit,
  124. self.out.GetParent().parent,
  125. )
  126. # copy from g.extension, potentially move to library
  127. def move_extracted_files(extract_dir, target_dir, files):
  128. """Fix state of extracted file by moving them to different diretcory
  129. When extracting, it is not clear what will be the root directory
  130. or if there will be one at all. So this function moves the files to
  131. a different directory in the way that if there was one directory extracted,
  132. the contained files are moved.
  133. """
  134. debug("move_extracted_files({0})".format(locals()))
  135. if len(files) == 1:
  136. shutil.copytree(os.path.join(extract_dir, files[0]), target_dir)
  137. else:
  138. if not os.path.exists(target_dir):
  139. os.mkdir(target_dir)
  140. for file_name in files:
  141. actual_file = os.path.join(extract_dir, file_name)
  142. if os.path.isdir(actual_file):
  143. # copy_tree() from distutils failed to create
  144. # directories before copying files time to time
  145. # (when copying to recently deleted directory)
  146. shutil.copytree(actual_file,
  147. os.path.join(target_dir, file_name))
  148. else:
  149. shutil.copy(actual_file, os.path.join(target_dir, file_name))
  150. # copy from g.extension, potentially move to library
  151. def extract_zip(name, directory, tmpdir):
  152. """Extract a ZIP file into a directory"""
  153. debug("extract_zip(name={name}, directory={directory},"
  154. " tmpdir={tmpdir})".format(name=name, directory=directory,
  155. tmpdir=tmpdir), 3)
  156. try:
  157. import zipfile
  158. zip_file = zipfile.ZipFile(name, mode='r')
  159. file_list = zip_file.namelist()
  160. # we suppose we can write to parent of the given dir
  161. # (supposing a tmp dir)
  162. extract_dir = os.path.join(tmpdir, 'extract_dir')
  163. os.mkdir(extract_dir)
  164. for subfile in file_list:
  165. # this should be safe in Python 2.7.4
  166. zip_file.extract(subfile, extract_dir)
  167. files = os.listdir(extract_dir)
  168. move_extracted_files(extract_dir=extract_dir,
  169. target_dir=directory, files=files)
  170. except zipfile.BadZipfile as error:
  171. raise DownloadError(_("ZIP file is unreadable: {0}").format(error))
  172. # copy from g.extension, potentially move to library
  173. def extract_tar(name, directory, tmpdir):
  174. """Extract a TAR or a similar file into a directory"""
  175. debug("extract_tar(name={name}, directory={directory},"
  176. " tmpdir={tmpdir})".format(name=name, directory=directory,
  177. tmpdir=tmpdir), 3)
  178. try:
  179. import tarfile # we don't need it anywhere else
  180. tar = tarfile.open(name)
  181. extract_dir = os.path.join(tmpdir, 'extract_dir')
  182. os.mkdir(extract_dir)
  183. tar.extractall(path=extract_dir)
  184. files = os.listdir(extract_dir)
  185. move_extracted_files(extract_dir=extract_dir,
  186. target_dir=directory, files=files)
  187. except tarfile.TarError as error:
  188. raise DownloadError(_("Archive file is unreadable: {0}").format(error))
  189. extract_tar.supported_formats = ['tar.gz', 'gz', 'bz2', 'tar', 'gzip', 'targz']
  190. # based on https://blog.shichao.io/2012/10/04/progress_speed_indicator_for_urlretrieve_in_python.html
  191. def reporthook(count, block_size, total_size):
  192. global start_time
  193. if count == 0:
  194. start_time = time.time()
  195. sys.stdout.write(
  196. _('Download in progress, wait until it is finished 0%'),
  197. )
  198. return
  199. if count % 100 != 0: # be less verbose
  200. return
  201. duration = time.time() - start_time
  202. progress_size = int(count * block_size)
  203. speed = int(progress_size / (1024 * duration))
  204. percent = int(count * block_size * 100 / total_size)
  205. sys.stdout.write(
  206. _("Download in progress, wait until it is finished "
  207. "{0}%, {1} MB, {2} KB/s, {3:.0f} seconds passed".format(
  208. percent, progress_size / (1024 * 1024), speed, duration,
  209. ),
  210. ),
  211. )
  212. # based on g.extension, potentially move to library
  213. def download_and_extract(source):
  214. """Download a file (archive) from URL and uncompress it"""
  215. tmpdir = tempfile.mkdtemp()
  216. Debug.msg(1, 'Tmpdir: {}'.format(tmpdir))
  217. directory = os.path.join(tmpdir, 'location')
  218. http_error_message = _(
  219. "Download file from <{url}>, "
  220. "return status code {code}, "
  221. )
  222. url_error_message = _(
  223. "Download file from <{url}>, "
  224. "failed. Check internet connection."
  225. )
  226. if source.endswith('.zip'):
  227. archive_name = os.path.join(tmpdir, 'location.zip')
  228. try:
  229. filename, headers = urlretrieve(source, archive_name, reporthook)
  230. except HTTPError as err:
  231. raise DownloadError(
  232. http_error_message.format(
  233. url=source,
  234. code=err,
  235. ),
  236. )
  237. except URLError:
  238. raise DownloadError(url_error_message.format(url=source))
  239. if headers.get('content-type', '') != 'application/zip':
  240. raise DownloadError(
  241. _("Download of <{url}> failed"
  242. " or file <{name}> is not a ZIP file").format(
  243. url=source, name=filename))
  244. extract_zip(name=archive_name, directory=directory, tmpdir=tmpdir)
  245. elif (source.endswith(".tar.gz") or
  246. source.rsplit('.', 1)[1] in extract_tar.supported_formats):
  247. if source.endswith(".tar.gz"):
  248. ext = "tar.gz"
  249. else:
  250. ext = source.rsplit('.', 1)[1]
  251. archive_name = os.path.join(tmpdir, 'location.' + ext)
  252. try:
  253. urlretrieve(source, archive_name, reporthook)
  254. except HTTPError as err:
  255. raise DownloadError(
  256. http_error_message.format(
  257. url=source,
  258. code=err,
  259. ),
  260. )
  261. except URLError:
  262. raise DownloadError(url_error_message.format(url=source))
  263. extract_tar(name=archive_name, directory=directory, tmpdir=tmpdir)
  264. else:
  265. # probably programmer error
  266. raise DownloadError(_("Unknown format '{0}'.").format(source))
  267. assert os.path.isdir(directory)
  268. return directory
  269. def download_location(url, name, database):
  270. """Wrapper to return DownloadError by value
  271. It also moves the location directory to the database.
  272. """
  273. try:
  274. # TODO: the unpacking could go right to the path (but less
  275. # robust) or replace copytree here with move
  276. directory = download_and_extract(source=url)
  277. destination = os.path.join(database, name)
  278. if not is_location_valid(directory):
  279. return _("Downloaded location is not valid")
  280. shutil.copytree(src=directory, dst=destination)
  281. try_rmdir(directory)
  282. except DownloadError as error:
  283. return error
  284. return None
  285. # based on grass.py (to be moved to future "grass.init")
  286. def is_location_valid(location):
  287. """Return True if GRASS Location is valid
  288. :param location: path of a Location
  289. """
  290. # DEFAULT_WIND file should not be required until you do something
  291. # that actually uses them. The check is just a heuristic; a directory
  292. # containing a PERMANENT/DEFAULT_WIND file is probably a GRASS
  293. # location, while a directory lacking it probably isn't.
  294. # TODO: perhaps we can relax this and require only permanent
  295. return os.access(os.path.join(location,
  296. "PERMANENT", "DEFAULT_WIND"), os.F_OK)
  297. def location_name_from_url(url):
  298. """Create location name from URL"""
  299. return url.rsplit('/', 1)[1].split('.', 1)[0].replace("-", "_").replace(" ", "_")
  300. DownloadDoneEvent, EVT_DOWNLOAD_DONE = NewEvent()
  301. class LocationDownloadPanel(wx.Panel):
  302. """Panel to select and initiate downloads of locations.
  303. Has a place to report errors to user and also any potential problems
  304. before the user hits the button.
  305. In the future, it can potentially show also some details about what
  306. will be downloaded. The choice widget can be also replaced.
  307. For the future, there can be multiple panels with different methods
  308. or sources, e.g. direct input of URL. These can be in separate tabs
  309. of one panel (perhaps sharing the common background download and
  310. message logic).
  311. """
  312. def __init__(self, parent, database, locations=LOCATIONS):
  313. """
  314. :param database: directory with G database to download to
  315. :param locations: list of dictionaries with label and url
  316. """
  317. wx.Panel.__init__(self, parent=parent)
  318. self.parent = parent
  319. self._last_downloaded_location_name = None
  320. self._download_in_progress = False
  321. self.database = database
  322. self.locations = locations
  323. self._abort_btn_label = _('Abort')
  324. self._abort_btn_tooltip = _('Abort download location')
  325. self.label = StaticText(
  326. parent=self,
  327. label=_("Select sample location to download:"))
  328. choices = []
  329. for item in self.locations:
  330. choices.append(item['label'])
  331. self.choice = wx.Choice(parent=self, choices=choices)
  332. self.choice.Bind(wx.EVT_CHOICE, self.OnChangeChoice)
  333. self.parent.download_button.Bind(wx.EVT_BUTTON, self.OnDownload)
  334. # TODO: add button for a link to an associated website?
  335. # TODO: add thumbnail for each location?
  336. # TODO: messages copied from gis_set.py, need this as API?
  337. self.message = StaticText(parent=self, size=(-1, 50))
  338. sys.stdout = RedirectText(self.message)
  339. # It is not clear if all wx versions supports color, so try-except.
  340. # The color itself may not be correct for all platforms/system settings
  341. # but in http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.SystemSettings.html
  342. # there is no 'warning' color.
  343. try:
  344. self.message.SetForegroundColour(wx.Colour(255, 0, 0))
  345. except AttributeError:
  346. pass
  347. self._layout()
  348. default = 0
  349. self.choice.SetSelection(default)
  350. self.CheckItem(self.locations[default])
  351. self.thread = gThread()
  352. def _layout(self):
  353. """Create and layout sizers"""
  354. vertical = wx.BoxSizer(wx.VERTICAL)
  355. self.sizer = vertical
  356. vertical.Add(self.label, proportion=0,
  357. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=10)
  358. vertical.Add(self.choice, proportion=0,
  359. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=10)
  360. vertical.AddStretchSpacer()
  361. vertical.Add(self.message, proportion=0,
  362. flag=wx.ALIGN_LEFT | wx.ALL | wx.EXPAND, border=10)
  363. self.SetSizer(vertical)
  364. vertical.Fit(self)
  365. self.Layout()
  366. self.SetMinSize(self.GetBestSize())
  367. def _change_download_btn_label(self, label=_('Do&wnload'),
  368. tooltip=_('Download selected location')):
  369. """Change download button label/tooltip"""
  370. if self.parent.download_button:
  371. self.parent.download_button.SetLabel(label)
  372. self.parent.download_button.SetToolTip(tooltip)
  373. def OnDownload(self, event):
  374. """Handle user-initiated action of download"""
  375. button_label = self.parent.download_button.GetLabel()
  376. if button_label in (_('Download'), _('Do&wnload')) :
  377. self._change_download_btn_label(
  378. label=self._abort_btn_label,
  379. tooltip=self._abort_btn_tooltip,
  380. )
  381. Debug.msg(1, "OnDownload")
  382. if self._download_in_progress:
  383. self._warning(_("Download in progress, wait until it is finished"))
  384. index = self.choice.GetSelection()
  385. self.DownloadItem(self.locations[index])
  386. else:
  387. self.parent.OnCancel()
  388. def DownloadItem(self, item):
  389. """Download the selected item"""
  390. Debug.msg(1, "DownloadItem: %s" % item)
  391. # similar code as in CheckItem
  392. url = item['url']
  393. dirname = location_name_from_url(url)
  394. destination = os.path.join(self.database, dirname)
  395. if os.path.exists(destination):
  396. self._error(_("Location named <%s> already exists,"
  397. " download canceled") % dirname)
  398. self._change_download_btn_label()
  399. return
  400. def download_complete_callback(event):
  401. self._download_in_progress = False
  402. errors = event.ret
  403. if errors:
  404. self._error(_("Download failed: %s") % errors)
  405. else:
  406. self._last_downloaded_location_name = dirname
  407. self._warning(_("Download completed. The downloaded sample data is listed "
  408. "in the location/mapset tabs upon closing of this window")
  409. )
  410. self._change_download_btn_label()
  411. def terminate_download_callback(event):
  412. self._download_in_progress = False
  413. request.urlcleanup()
  414. sys.stdout.write("Download aborted")
  415. self.thread = gThread()
  416. self._change_download_btn_label()
  417. self._download_in_progress = True
  418. self._warning(_("Download in progress, wait until it is finished"))
  419. self.thread.Run(callable=download_location,
  420. url=url, name=dirname, database=self.database,
  421. ondone=download_complete_callback,
  422. onterminate=terminate_download_callback)
  423. def OnChangeChoice(self, event):
  424. """React to user changing the selection"""
  425. index = self.choice.GetSelection()
  426. self.CheckItem(self.locations[index])
  427. def CheckItem(self, item):
  428. """Check what user selected and report potential issues"""
  429. # similar code as in DownloadItem
  430. url = item['url']
  431. dirname = location_name_from_url(url)
  432. destination = os.path.join(self.database, dirname)
  433. if os.path.exists(destination):
  434. self._warning(_("Location named <%s> already exists,"
  435. " rename it first") % dirname)
  436. self.parent.download_button.SetLabel(label=_('Download'))
  437. return
  438. else:
  439. self._clearMessage()
  440. def GetLocation(self):
  441. """Get the name of the last location downloaded by the user"""
  442. return self._last_downloaded_location_name
  443. def _warning(self, text):
  444. """Displays a warning, hint or info message to the user.
  445. This function can be used for all kinds of messages except for
  446. error messages.
  447. .. note::
  448. There is no cleaning procedure. You should call
  449. _clearMessage() when you know that there is everything
  450. correct.
  451. """
  452. sys.stdout.write(text)
  453. self.sizer.Layout()
  454. def _error(self, text):
  455. """Displays a error message to the user.
  456. This function should be used only when something serious and unexpected
  457. happens, otherwise _showWarning should be used.
  458. .. note::
  459. There is no cleaning procedure. You should call
  460. _clearMessage() when you know that there is everything
  461. correct.
  462. """
  463. sys.stdout.write(_("Error: {text}").format(text=text))
  464. self.sizer.Layout()
  465. def _clearMessage(self):
  466. """Clears/hides the error message."""
  467. # we do no hide widget
  468. # because we do not want the dialog to change the size
  469. self.message.SetLabel("")
  470. self.sizer.Layout()
  471. class LocationDownloadDialog(wx.Dialog):
  472. """Dialog for download of locations
  473. Contains the panel and Cancel button.
  474. """
  475. def __init__(self, parent, database,
  476. title=_("GRASS GIS Location Download")):
  477. """
  478. :param database: database to download the location to
  479. :param title: window title if the default is not appropriate
  480. """
  481. wx.Dialog.__init__(self, parent=parent, title=title)
  482. cancel_button = Button(self, id=wx.ID_CANCEL)
  483. self.download_button = Button(parent=self, id=wx.ID_ANY,
  484. label=_("Do&wnload"))
  485. self.download_button.SetToolTip(_("Download selected location"))
  486. self.panel = LocationDownloadPanel(parent=self, database=database)
  487. cancel_button.Bind(wx.EVT_BUTTON, self.OnCancel)
  488. self.Bind(wx.EVT_CLOSE, self.OnCancel)
  489. self.sizer = wx.BoxSizer(wx.VERTICAL)
  490. self.sizer.Add(self.panel, proportion=1, flag=wx.EXPAND)
  491. button_sizer = wx.StdDialogButtonSizer()
  492. button_sizer.Add(
  493. cancel_button,
  494. proportion=0,
  495. flag=wx.EXPAND | wx.LEFT | wx.RIGHT,
  496. border=5,
  497. )
  498. button_sizer.Add(
  499. self.download_button,
  500. proportion=0,
  501. flag=wx.EXPAND | wx.LEFT | wx.RIGHT,
  502. border=5,
  503. )
  504. button_sizer.Realize()
  505. self.sizer.Add(button_sizer, proportion=0,
  506. flag=wx.ALIGN_RIGHT | wx.TOP | wx.BOTTOM,
  507. border=10)
  508. self.SetSizer(self.sizer)
  509. self.sizer.Fit(self)
  510. self.Layout()
  511. def GetLocation(self):
  512. """Get the name of the last location downloaded by the user"""
  513. return self.panel.GetLocation()
  514. def OnCancel(self, event=None):
  515. if self.panel._download_in_progress:
  516. # running thread
  517. dlg = wx.MessageDialog(parent=self,
  518. message=_("Do you want to cancel location download?"),
  519. caption=_("Abort download"),
  520. style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION | wx.CENTRE
  521. )
  522. ret = dlg.ShowModal()
  523. dlg.Destroy()
  524. if ret == wx.ID_NO:
  525. return
  526. else:
  527. self.panel.thread.Terminate()
  528. self.panel._change_download_btn_label()
  529. if event:
  530. self.EndModal(wx.ID_CANCEL)
  531. def main():
  532. """Tests the download dialog"""
  533. if len(sys.argv) < 2:
  534. sys.exit("Provide a test directory")
  535. database = sys.argv[1]
  536. app = wx.App()
  537. if len(sys.argv) == 2 or sys.argv[2] == 'dialog':
  538. window = LocationDownloadDialog(parent=None, database=database)
  539. window.ShowModal()
  540. location = window.GetLocation()
  541. if location:
  542. print(location)
  543. window.Destroy()
  544. elif sys.argv[2] == 'panel':
  545. window = wx.Dialog(parent=None)
  546. panel = LocationDownloadPanel(parent=window, database=database)
  547. window.ShowModal()
  548. location = panel.GetLocation()
  549. if location:
  550. print(location)
  551. window.Destroy()
  552. else:
  553. print("Unknown settings: try dialog or panel")
  554. app.MainLoop()
  555. if __name__ == '__main__':
  556. main()