locdownload.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  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.utils import _
  34. from core.gthread import gThread
  35. from gui_core.wrap import Button, StaticText
  36. # TODO: labels (and descriptions) translatable?
  37. LOCATIONS = [
  38. {
  39. "label": "Complete NC location",
  40. "url": "https://grass.osgeo.org/sampledata/north_carolina/nc_spm_08_grass7.tar.gz",
  41. },
  42. {
  43. "label": "Basic NC location",
  44. "url": "https://grass.osgeo.org/sampledata/north_carolina/nc_basic_spm_grass7.tar.gz",
  45. },
  46. {
  47. "label": "World location in LatLong/WGS84",
  48. "url": "https://grass.osgeo.org/sampledata/worldlocation.tar.gz",
  49. },
  50. {
  51. "label": "Spearfish (SD) location",
  52. "url": "https://grass.osgeo.org/sampledata/spearfish_grass70data-0.3.tar.gz",
  53. },
  54. {
  55. "label": "Piemonte, Italy data set",
  56. "url": "http://geodati.fmach.it/gfoss_geodata/libro_gfoss/grassdata_piemonte_utm32n_wgs84_grass7.tar.gz",
  57. },
  58. {
  59. "label": "Slovakia 3D precipitation voxel data set",
  60. "url": "https://grass.osgeo.org/uploads/grass/sampledata/slovakia3d_grass7.tar.gz",
  61. },
  62. {
  63. "label": "Fire simulation sample data",
  64. "url": "https://grass.osgeo.org/sampledata/fire_grass6data.tar.gz",
  65. },
  66. {
  67. "label": "GISMentors location, Czech Republic",
  68. "url": "http://training.gismentors.eu/geodata/grass/gismentors.zip",
  69. },
  70. ]
  71. class DownloadError(Exception):
  72. """Error happened during download or when processing the file"""
  73. pass
  74. class RedirectText(object):
  75. def __init__(self, window):
  76. self.out = window
  77. def write(self, string):
  78. try:
  79. wx.CallAfter(self.out.SetLabel, string)
  80. except:
  81. # window closed -> PyDeadObjectError
  82. pass
  83. # copy from g.extension, potentially move to library
  84. def move_extracted_files(extract_dir, target_dir, files):
  85. """Fix state of extracted file by moving them to different diretcory
  86. When extracting, it is not clear what will be the root directory
  87. or if there will be one at all. So this function moves the files to
  88. a different directory in the way that if there was one directory extracted,
  89. the contained files are moved.
  90. """
  91. debug("move_extracted_files({0})".format(locals()))
  92. if len(files) == 1:
  93. shutil.copytree(os.path.join(extract_dir, files[0]), target_dir)
  94. else:
  95. if not os.path.exists(target_dir):
  96. os.mkdir(target_dir)
  97. for file_name in files:
  98. actual_file = os.path.join(extract_dir, file_name)
  99. if os.path.isdir(actual_file):
  100. # copy_tree() from distutils failed to create
  101. # directories before copying files time to time
  102. # (when copying to recently deleted directory)
  103. shutil.copytree(actual_file,
  104. os.path.join(target_dir, file_name))
  105. else:
  106. shutil.copy(actual_file, os.path.join(target_dir, file_name))
  107. # copy from g.extension, potentially move to library
  108. def extract_zip(name, directory, tmpdir):
  109. """Extract a ZIP file into a directory"""
  110. debug("extract_zip(name={name}, directory={directory},"
  111. " tmpdir={tmpdir})".format(name=name, directory=directory,
  112. tmpdir=tmpdir), 3)
  113. try:
  114. import zipfile
  115. zip_file = zipfile.ZipFile(name, mode='r')
  116. file_list = zip_file.namelist()
  117. # we suppose we can write to parent of the given dir
  118. # (supposing a tmp dir)
  119. extract_dir = os.path.join(tmpdir, 'extract_dir')
  120. os.mkdir(extract_dir)
  121. for subfile in file_list:
  122. # this should be safe in Python 2.7.4
  123. zip_file.extract(subfile, extract_dir)
  124. files = os.listdir(extract_dir)
  125. move_extracted_files(extract_dir=extract_dir,
  126. target_dir=directory, files=files)
  127. except zipfile.BadZipfile as error:
  128. raise DownloadError(_("ZIP file is unreadable: {0}").format(error))
  129. # copy from g.extension, potentially move to library
  130. def extract_tar(name, directory, tmpdir):
  131. """Extract a TAR or a similar file into a directory"""
  132. debug("extract_tar(name={name}, directory={directory},"
  133. " tmpdir={tmpdir})".format(name=name, directory=directory,
  134. tmpdir=tmpdir), 3)
  135. try:
  136. import tarfile # we don't need it anywhere else
  137. tar = tarfile.open(name)
  138. extract_dir = os.path.join(tmpdir, 'extract_dir')
  139. os.mkdir(extract_dir)
  140. tar.extractall(path=extract_dir)
  141. files = os.listdir(extract_dir)
  142. move_extracted_files(extract_dir=extract_dir,
  143. target_dir=directory, files=files)
  144. except tarfile.TarError as error:
  145. raise DownloadError(_("Archive file is unreadable: {0}").format(error))
  146. extract_tar.supported_formats = ['tar.gz', 'gz', 'bz2', 'tar', 'gzip', 'targz']
  147. # based on https://blog.shichao.io/2012/10/04/progress_speed_indicator_for_urlretrieve_in_python.html
  148. def reporthook(count, block_size, total_size):
  149. global start_time
  150. if count == 0:
  151. start_time = time.time()
  152. sys.stdout.write("Download in progress, wait until it is finished\n0%")
  153. return
  154. if count % 100 != 0: # be less verbose
  155. return
  156. duration = time.time() - start_time
  157. progress_size = int(count * block_size)
  158. speed = int(progress_size / (1024 * duration))
  159. percent = int(count * block_size * 100 / total_size)
  160. sys.stdout.write("Download in progress, wait until it is finished\n{0}%, {1} MB, {2} KB/s, {3:.0f} seconds passed".format(
  161. percent, progress_size / (1024 * 1024), speed, duration
  162. ))
  163. # based on g.extension, potentially move to library
  164. def download_and_extract(source):
  165. """Download a file (archive) from URL and uncompress it"""
  166. tmpdir = tempfile.mkdtemp()
  167. Debug.msg(1, 'Tmpdir: {}'.format(tmpdir))
  168. directory = os.path.join(tmpdir, 'location')
  169. if source.endswith('.zip'):
  170. archive_name = os.path.join(tmpdir, 'location.zip')
  171. filename, headers = urlretrieve(source, archive_name, reporthook)
  172. if headers.get('content-type', '') != 'application/zip':
  173. raise DownloadError(
  174. _("Download of <{url}> failed"
  175. " or file <{name}> is not a ZIP file").format(
  176. url=source, name=filename))
  177. extract_zip(name=archive_name, directory=directory, tmpdir=tmpdir)
  178. elif (source.endswith(".tar.gz") or
  179. source.rsplit('.', 1)[1] in extract_tar.supported_formats):
  180. if source.endswith(".tar.gz"):
  181. ext = "tar.gz"
  182. else:
  183. ext = source.rsplit('.', 1)[1]
  184. archive_name = os.path.join(tmpdir, 'location.' + ext)
  185. urlretrieve(source, archive_name, reporthook)
  186. # TODO: error handling for urlretrieve
  187. extract_tar(name=archive_name, directory=directory, tmpdir=tmpdir)
  188. else:
  189. # probably programmer error
  190. raise DownloadError(_("Unknown format '{0}'.").format(source))
  191. assert os.path.isdir(directory)
  192. return directory
  193. def download_location(url, name, database):
  194. """Wrapper to return DownloadError by value
  195. It also moves the location directory to the database.
  196. """
  197. try:
  198. # TODO: the unpacking could go right to the path (but less
  199. # robust) or replace copytree here with move
  200. directory = download_and_extract(source=url)
  201. destination = os.path.join(database, name)
  202. if not is_location_valid(directory):
  203. return _("Downloaded location is not valid")
  204. shutil.copytree(src=directory, dst=destination)
  205. try_rmdir(directory)
  206. except DownloadError as error:
  207. return error
  208. return None
  209. # based on grass.py (to be moved to future "grass.init")
  210. def is_location_valid(location):
  211. """Return True if GRASS Location is valid
  212. :param location: path of a Location
  213. """
  214. # DEFAULT_WIND file should not be required until you do something
  215. # that actually uses them. The check is just a heuristic; a directory
  216. # containing a PERMANENT/DEFAULT_WIND file is probably a GRASS
  217. # location, while a directory lacking it probably isn't.
  218. # TODO: perhaps we can relax this and require only permanent
  219. return os.access(os.path.join(location,
  220. "PERMANENT", "DEFAULT_WIND"), os.F_OK)
  221. def location_name_from_url(url):
  222. """Create location name from URL"""
  223. return url.rsplit('/', 1)[1].split('.', 1)[0].replace("-", "_").replace(" ", "_")
  224. DownloadDoneEvent, EVT_DOWNLOAD_DONE = NewEvent()
  225. class LocationDownloadPanel(wx.Panel):
  226. """Panel to select and initiate downloads of locations.
  227. Has a place to report errors to user and also any potential problems
  228. before the user hits the button.
  229. In the future, it can potentially show also some details about what
  230. will be downloaded. The choice widget can be also replaced.
  231. For the future, there can be multiple panels with different methods
  232. or sources, e.g. direct input of URL. These can be in separate tabs
  233. of one panel (perhaps sharing the common background download and
  234. message logic).
  235. """
  236. def __init__(self, parent, database, locations=LOCATIONS):
  237. """
  238. :param database: directory with G database to download to
  239. :param locations: list of dictionaries with label and url
  240. """
  241. wx.Panel.__init__(self, parent=parent)
  242. self._last_downloaded_location_name = None
  243. self._download_in_progress = False
  244. self.database = database
  245. self.locations = locations
  246. self.label = StaticText(
  247. parent=self,
  248. label=_("Select sample location to download:"))
  249. choices = []
  250. for item in self.locations:
  251. choices.append(item['label'])
  252. self.choice = wx.Choice(parent=self, choices=choices)
  253. self.choice.Bind(wx.EVT_CHOICE, self.OnChangeChoice)
  254. self.download_button = Button(parent=self, id=wx.ID_ANY,
  255. label=_("Do&wnload"))
  256. self.download_button.SetToolTip(_("Download selected location"))
  257. self.download_button.Bind(wx.EVT_BUTTON, self.OnDownload)
  258. # TODO: add button for a link to an associated website?
  259. # TODO: add thumbnail for each location?
  260. # TODO: messages copied from gis_set.py, need this as API?
  261. self.message = StaticText(parent=self, size=(-1, 50))
  262. sys.stdout = RedirectText(self.message)
  263. # It is not clear if all wx versions supports color, so try-except.
  264. # The color itself may not be correct for all platforms/system settings
  265. # but in http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.SystemSettings.html
  266. # there is no 'warning' color.
  267. try:
  268. self.message.SetForegroundColour(wx.Colour(255, 0, 0))
  269. except AttributeError:
  270. pass
  271. self._layout()
  272. default = 0
  273. self.choice.SetSelection(default)
  274. self.CheckItem(self.locations[default])
  275. self.thread = gThread()
  276. def _layout(self):
  277. """Create and layout sizers"""
  278. vertical = wx.BoxSizer(wx.VERTICAL)
  279. self.sizer = vertical
  280. vertical.Add(self.label, proportion=0,
  281. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=10)
  282. vertical.Add(self.choice, proportion=0,
  283. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT, border=10)
  284. button_sizer = wx.BoxSizer(wx.HORIZONTAL)
  285. button_sizer.AddStretchSpacer()
  286. button_sizer.Add(self.download_button, proportion=0)
  287. vertical.Add(button_sizer, proportion=0,
  288. flag=wx.EXPAND | wx.TOP | wx.LEFT | wx.RIGHT | wx.ALIGN_RIGHT, border=10)
  289. vertical.AddStretchSpacer()
  290. vertical.Add(self.message, proportion=0,
  291. flag=wx.ALIGN_CENTER_VERTICAL |
  292. 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()