locdownload.py 19 KB

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