locdownload.py 19 KB

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