locdownload.py 19 KB

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