locdownload.py 23 KB

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