We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Helioviewer is not working, homepage is downloaded instead of the requested image.
Few days ago, the helioviewer interface not download the image requested.

```
from sunpy.net.helioviewer import HelioviewerClient
hv = HelioviewerClient()
hv.download_png('2012/07/16 10:08:00', 4.8, "[SDO,AIA,AIA,171,1,100],[SOHO,LASCO,C2,white-light,1,100]", x1=-2800, x2=2800, y1=-2800, y2=2800, directory='~/Desktop')   # doctest: +SKIP
```

The file downloaded is the homepage from helioviewer!


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `sunpy/net/helioviewer.py`
Content:
```
1 """
2 This module provides a wrapper around the Helioviewer API.
3 """
4 from __future__ import absolute_import
5 
6 #pylint: disable=E1101,F0401,W0231
7 
8 __author__ = ["Keith Hughitt"]
9 __email__ = "keith.hughitt@nasa.gov"
10 
11 import os
12 import json
13 import codecs
14 import sunpy
15 from sunpy.time import parse_time
16 from sunpy.util.net import download_fileobj
17 
18 from sunpy.extern.six.moves import urllib
19 
20 __all__ = ['HelioviewerClient']
21 
22 
23 class HelioviewerClient(object):
24     """Helioviewer.org Client"""
25     def __init__(self, url="http://helioviewer.org/api/"):
26         self._api = url
27 
28     def get_data_sources(self, **kwargs):
29         """Returns a structured list of datasources available at Helioviewer.org"""
30         params = {"action": "getDataSources"}
31         params.update(kwargs)
32 
33         return self._get_json(params)
34 
35     def get_closest_image(self, date, **kwargs):
36         """Finds the closest image available for the specified source and date.
37 
38         For more information on what types of requests are available and the
39         expected usage for the response, consult the Helioviewer
40         API documentation: http://helioviewer.org/api
41 
42         Parameters
43         ----------
44         date : `datetime.datetime`, `str`
45             A string or datetime object for the desired date of the image
46         observatory : string
47             (Optional) Observatory name
48         instrument : string
49             (Optional) instrument name
50         detector : string
51             (Optional) detector name
52         measurement : string
53             (Optional) measurement name
54         sourceId : int
55             (Optional) data source id
56 
57         Returns
58         -------
59         out : `dict`
60             A dictionary containing meta-information for the closest image matched
61 
62         Examples
63         --------
64         >>> from sunpy.net import HelioviewerClient
65 
66         >>> client = HelioviewerClient()
67         >>> metadata = client.get_closest_image('2012/01/01', sourceId=11)
68         >>> print(metadata['date'])
69         2012-01-01 00:00:07
70         """
71         params = {
72             "action": "getClosestImage",
73             "date": self._format_date(date)
74         }
75         params.update(kwargs)
76 
77         response = self._get_json(params)
78 
79         # Cast date string to DateTime
80         response['date'] = parse_time(response['date'])
81 
82         return response
83 
84     def download_jp2(self, date, directory=None, overwrite=False, **kwargs):
85         """
86         Downloads the JPEG 2000 that most closely matches the specified time and
87         data source.
88 
89         The data source may be specified either using it's sourceId from the
90         get_data_sources query, or a combination of observatory, instrument,
91         detector and measurement.
92 
93         Parameters
94         ----------
95         date : `datetime.datetime`, string
96             A string or datetime object for the desired date of the image
97         directory : string
98             (Optional) Directory to download JPEG 2000 image to.
99         observatory : string
100             (Optional) Observatory name
101         instrument : string
102             (Optional) instrument name
103         detector : string
104             (Optional) detector name
105         measurement : string
106             (Optional) measurement name
107         sourceId : int
108             (Optional) data source id
109         jpip : bool
110             (Optional) Returns a JPIP URI if set to True
111 
112         Returns
113         -------
114         out : string
115             Returns a filepath to the downloaded JPEG 2000 image or a URL if
116             the "jpip" parameter is set to True.
117 
118         Examples
119         --------
120         >>> import sunpy.map
121         >>> from sunpy.net import helioviewer
122         >>> hv = helioviewer.HelioviewerClient()
123         >>> filepath = hv.download_jp2('2012/07/03 14:30:00', observatory='SDO', instrument='AIA', detector='AIA', measurement='171')   # doctest: +SKIP
124         >>> aia = sunpy.map.Map(filepath)   # doctest: +SKIP
125         >>> aia.peek()   # doctest: +SKIP
126 
127         >>> data_sources = hv.get_data_sources()
128         >>> hv.download_jp2('2012/07/03 14:30:00', sourceId=data_sources['SOHO']['LASCO']['C2']['white-light']['sourceId'])   # doctest: +SKIP
129         """
130         params = {
131             "action": "getJP2Image",
132             "date": self._format_date(date)
133         }
134         params.update(kwargs)
135 
136         # JPIP URL response
137         if 'jpip' in kwargs:
138             return self._get_json(params)
139 
140         return self._get_file(params, directory, overwrite=overwrite)
141 
142     def download_png(self, date, image_scale, layers, directory=None,
143                      overwrite=False, **kwargs):
144         """Downloads a PNG image using data from Helioviewer.org.
145 
146         Returns a single image containing all layers/image types requested.
147         If an image is not available for the date requested the closest
148         available image is returned. The region to be included in the
149         image may be specified using either the top-left and bottom-right
150         coordinates in arc-seconds, or a center point in arc-seconds and a
151         width and height in pixels. See the Helioviewer.org API Coordinates
152         Appendix for more information about working with coordinates in
153         Helioviewer.org.
154 
155         Parameters
156         ----------
157         date : `datetime.datetime`, string
158             A string or datetime object for the desired date of the image
159         image_scale : float
160             The zoom scale of the image. Default scales that can be used are
161             0.6, 1.2, 2.4, and so on, increasing or decreasing by a factor
162             of 2. The full-res scale of an AIA image is 0.6.
163         layers : string
164             Each layer string is comma-separated with these values, e.g.:
165             "[sourceId,visible,opacity]" or "[obs,inst,det,meas,visible,opacity]"
166             Multiple layer string are by commas: "[layer1],[layer2],[layer3]"
167         directory : string
168             (Optional)  Directory to download JPEG 2000 image to.
169         x1 : float
170             (Optional) The offset of the image's left boundary from the center
171             of the sun, in arcseconds.
172         y1 : float
173             (Optional) The offset of the image's top boundary from the center
174             of the sun, in arcseconds.
175         x2 : float
176             (Optional) The offset of the image's right boundary from the
177             center of the sun, in arcseconds.
178         y2 : float
179             (Optional) The offset of the image's bottom boundary from the
180             center of the sun, in arcseconds.
181         x0 : float
182             (Optional) The horizontal offset from the center of the Sun.
183         y0 : float
184             (Optional) The vertical offset from the center of the Sun.
185         width : int
186             (Optional) Width of the image in pixels (Maximum: 1920).
187         height : int
188             (Optional) Height of the image in pixels (Maximum: 1200).
189         watermark
190             (Optional) Whether or not the include the timestamps and the
191             Helioviewer.org logo in the image (Default=True).
192 
193         Returns
194         -------
195         out : string
196             filepath to the PNG image
197 
198         Examples
199         --------
200         >>> from sunpy.net.helioviewer import HelioviewerClient
201         >>> hv = HelioviewerClient()
202         >>> hv.download_png('2012/07/16 10:08:00', 2.4, "[SDO,AIA,AIA,171,1,100]", x0=0, y0=0, width=1024, height=1024)   # doctest: +SKIP
203         >>> hv.download_png('2012/07/16 10:08:00', 4.8, "[SDO,AIA,AIA,171,1,100],[SOHO,LASCO,C2,white-light,1,100]", x1=-2800, x2=2800, y1=-2800, y2=2800, directory='~/Desktop')   # doctest: +SKIP
204         """
205         params = {
206             "action": "takeScreenshot",
207             "date": self._format_date(date),
208             "imageScale": image_scale,
209             "layers": layers,
210             "display": True
211         }
212         params.update(kwargs)
213 
214         return self._get_file(params, directory, overwrite=overwrite)
215 
216     def is_online(self):
217         """Returns True if Helioviewer is online and available."""
218         try:
219             self.get_data_sources()
220         except urllib.error.URLError:
221             return False
222 
223         return True
224 
225     def _get_json(self, params):
226         """Returns a JSON result as a string"""
227         reader = codecs.getreader("utf-8")
228         response = self._request(params)
229         return json.load(reader(response))
230 
231     def _get_file(self, params, directory=None, overwrite=False):
232         """Downloads a file and return the filepath to that file"""
233         # Query Helioviewer.org
234         if directory is None:
235             directory = sunpy.config.get('downloads', 'download_dir')
236         else:
237             directory = os.path.abspath(os.path.expanduser(directory))
238 
239         response = self._request(params)
240         try:
241             filepath = download_fileobj(response, directory, overwrite=overwrite)
242         finally:
243             response.close()
244 
245         return filepath
246 
247     def _request(self, params):
248         """Sends an API request and returns the result
249 
250         Parameters
251         ----------
252         params : `dict`
253             Parameters to send
254 
255         Returns
256         -------
257         out : result of request
258         """
259         response = urllib.request.urlopen(
260             self._api, urllib.parse.urlencode(params).encode('utf-8'))
261 
262         return response
263 
264     def _format_date(self, date):
265         """Formats a date for Helioviewer API requests"""
266         return parse_time(date).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + "Z"
267
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/sunpy/net/helioviewer.py b/sunpy/net/helioviewer.py
--- a/sunpy/net/helioviewer.py
+++ b/sunpy/net/helioviewer.py
@@ -22,11 +22,18 @@
 
 class HelioviewerClient(object):
     """Helioviewer.org Client"""
-    def __init__(self, url="http://helioviewer.org/api/"):
+    def __init__(self, url="http://legacy.helioviewer.org/api/"):
+        """
+        url : location of the Helioviewer API.  The default location points to
+            version 1 of the API.  Version 1 of the Helioviewer API is
+            currently planned to be supported until the end of April 2017.
+        """
         self._api = url
 
     def get_data_sources(self, **kwargs):
-        """Returns a structured list of datasources available at Helioviewer.org"""
+        """
+        Returns a structured list of datasources available at helioviewer.org.
+        """
         params = {"action": "getDataSources"}
         params.update(kwargs)
 
@@ -36,8 +43,8 @@
         """Finds the closest image available for the specified source and date.
 
         For more information on what types of requests are available and the
-        expected usage for the response, consult the Helioviewer
-        API documentation: http://helioviewer.org/api
+        expected usage for the response, consult the Helioviewer API
+        documentation: http://legacy.helioviewer.org/api/docs/v1/ .
 
         Parameters
         ----------

{"golden_diff": "diff --git a/sunpy/net/helioviewer.py b/sunpy/net/helioviewer.py\n--- a/sunpy/net/helioviewer.py\n+++ b/sunpy/net/helioviewer.py\n@@ -22,11 +22,18 @@\n \n class HelioviewerClient(object):\n     \"\"\"Helioviewer.org Client\"\"\"\n-    def __init__(self, url=\"http://helioviewer.org/api/\"):\n+    def __init__(self, url=\"http://legacy.helioviewer.org/api/\"):\n+        \"\"\"\n+        url : location of the Helioviewer API.  The default location points to\n+            version 1 of the API.  Version 1 of the Helioviewer API is\n+            currently planned to be supported until the end of April 2017.\n+        \"\"\"\n         self._api = url\n \n     def get_data_sources(self, **kwargs):\n-        \"\"\"Returns a structured list of datasources available at Helioviewer.org\"\"\"\n+        \"\"\"\n+        Returns a structured list of datasources available at helioviewer.org.\n+        \"\"\"\n         params = {\"action\": \"getDataSources\"}\n         params.update(kwargs)\n \n@@ -36,8 +43,8 @@\n         \"\"\"Finds the closest image available for the specified source and date.\n \n         For more information on what types of requests are available and the\n-        expected usage for the response, consult the Helioviewer\n-        API documentation: http://helioviewer.org/api\n+        expected usage for the response, consult the Helioviewer API\n+        documentation: http://legacy.helioviewer.org/api/docs/v1/ .\n \n         Parameters\n         ----------\n", "issue": "Helioviewer is not working, homepage is downloaded instead of the requested image.\nFew days ago, the helioviewer interface not download the image requested.\n\n```\nfrom sunpy.net.helioviewer import HelioviewerClient\nhv = HelioviewerClient()\nhv.download_png('2012/07/16 10:08:00', 4.8, \"[SDO,AIA,AIA,171,1,100],[SOHO,LASCO,C2,white-light,1,100]\", x1=-2800, x2=2800, y1=-2800, y2=2800, directory='~/Desktop')   # doctest: +SKIP\n```\n\nThe file downloaded is the homepage from helioviewer!\n\n", "before_files": [{"content": "\"\"\"\nThis module provides a wrapper around the Helioviewer API.\n\"\"\"\nfrom __future__ import absolute_import\n\n#pylint: disable=E1101,F0401,W0231\n\n__author__ = [\"Keith Hughitt\"]\n__email__ = \"keith.hughitt@nasa.gov\"\n\nimport os\nimport json\nimport codecs\nimport sunpy\nfrom sunpy.time import parse_time\nfrom sunpy.util.net import download_fileobj\n\nfrom sunpy.extern.six.moves import urllib\n\n__all__ = ['HelioviewerClient']\n\n\nclass HelioviewerClient(object):\n    \"\"\"Helioviewer.org Client\"\"\"\n    def __init__(self, url=\"http://helioviewer.org/api/\"):\n        self._api = url\n\n    def get_data_sources(self, **kwargs):\n        \"\"\"Returns a structured list of datasources available at Helioviewer.org\"\"\"\n        params = {\"action\": \"getDataSources\"}\n        params.update(kwargs)\n\n        return self._get_json(params)\n\n    def get_closest_image(self, date, **kwargs):\n        \"\"\"Finds the closest image available for the specified source and date.\n\n        For more information on what types of requests are available and the\n        expected usage for the response, consult the Helioviewer\n        API documentation: http://helioviewer.org/api\n\n        Parameters\n        ----------\n        date : `datetime.datetime`, `str`\n            A string or datetime object for the desired date of the image\n        observatory : string\n            (Optional) Observatory name\n        instrument : string\n            (Optional) instrument name\n        detector : string\n            (Optional) detector name\n        measurement : string\n            (Optional) measurement name\n        sourceId : int\n            (Optional) data source id\n\n        Returns\n        -------\n        out : `dict`\n            A dictionary containing meta-information for the closest image matched\n\n        Examples\n        --------\n        >>> from sunpy.net import HelioviewerClient\n\n        >>> client = HelioviewerClient()\n        >>> metadata = client.get_closest_image('2012/01/01', sourceId=11)\n        >>> print(metadata['date'])\n        2012-01-01 00:00:07\n        \"\"\"\n        params = {\n            \"action\": \"getClosestImage\",\n            \"date\": self._format_date(date)\n        }\n        params.update(kwargs)\n\n        response = self._get_json(params)\n\n        # Cast date string to DateTime\n        response['date'] = parse_time(response['date'])\n\n        return response\n\n    def download_jp2(self, date, directory=None, overwrite=False, **kwargs):\n        \"\"\"\n        Downloads the JPEG 2000 that most closely matches the specified time and\n        data source.\n\n        The data source may be specified either using it's sourceId from the\n        get_data_sources query, or a combination of observatory, instrument,\n        detector and measurement.\n\n        Parameters\n        ----------\n        date : `datetime.datetime`, string\n            A string or datetime object for the desired date of the image\n        directory : string\n            (Optional) Directory to download JPEG 2000 image to.\n        observatory : string\n            (Optional) Observatory name\n        instrument : string\n            (Optional) instrument name\n        detector : string\n            (Optional) detector name\n        measurement : string\n            (Optional) measurement name\n        sourceId : int\n            (Optional) data source id\n        jpip : bool\n            (Optional) Returns a JPIP URI if set to True\n\n        Returns\n        -------\n        out : string\n            Returns a filepath to the downloaded JPEG 2000 image or a URL if\n            the \"jpip\" parameter is set to True.\n\n        Examples\n        --------\n        >>> import sunpy.map\n        >>> from sunpy.net import helioviewer\n        >>> hv = helioviewer.HelioviewerClient()\n        >>> filepath = hv.download_jp2('2012/07/03 14:30:00', observatory='SDO', instrument='AIA', detector='AIA', measurement='171')   # doctest: +SKIP\n        >>> aia = sunpy.map.Map(filepath)   # doctest: +SKIP\n        >>> aia.peek()   # doctest: +SKIP\n\n        >>> data_sources = hv.get_data_sources()\n        >>> hv.download_jp2('2012/07/03 14:30:00', sourceId=data_sources['SOHO']['LASCO']['C2']['white-light']['sourceId'])   # doctest: +SKIP\n        \"\"\"\n        params = {\n            \"action\": \"getJP2Image\",\n            \"date\": self._format_date(date)\n        }\n        params.update(kwargs)\n\n        # JPIP URL response\n        if 'jpip' in kwargs:\n            return self._get_json(params)\n\n        return self._get_file(params, directory, overwrite=overwrite)\n\n    def download_png(self, date, image_scale, layers, directory=None,\n                     overwrite=False, **kwargs):\n        \"\"\"Downloads a PNG image using data from Helioviewer.org.\n\n        Returns a single image containing all layers/image types requested.\n        If an image is not available for the date requested the closest\n        available image is returned. The region to be included in the\n        image may be specified using either the top-left and bottom-right\n        coordinates in arc-seconds, or a center point in arc-seconds and a\n        width and height in pixels. See the Helioviewer.org API Coordinates\n        Appendix for more information about working with coordinates in\n        Helioviewer.org.\n\n        Parameters\n        ----------\n        date : `datetime.datetime`, string\n            A string or datetime object for the desired date of the image\n        image_scale : float\n            The zoom scale of the image. Default scales that can be used are\n            0.6, 1.2, 2.4, and so on, increasing or decreasing by a factor\n            of 2. The full-res scale of an AIA image is 0.6.\n        layers : string\n            Each layer string is comma-separated with these values, e.g.:\n            \"[sourceId,visible,opacity]\" or \"[obs,inst,det,meas,visible,opacity]\"\n            Multiple layer string are by commas: \"[layer1],[layer2],[layer3]\"\n        directory : string\n            (Optional)  Directory to download JPEG 2000 image to.\n        x1 : float\n            (Optional) The offset of the image's left boundary from the center\n            of the sun, in arcseconds.\n        y1 : float\n            (Optional) The offset of the image's top boundary from the center\n            of the sun, in arcseconds.\n        x2 : float\n            (Optional) The offset of the image's right boundary from the\n            center of the sun, in arcseconds.\n        y2 : float\n            (Optional) The offset of the image's bottom boundary from the\n            center of the sun, in arcseconds.\n        x0 : float\n            (Optional) The horizontal offset from the center of the Sun.\n        y0 : float\n            (Optional) The vertical offset from the center of the Sun.\n        width : int\n            (Optional) Width of the image in pixels (Maximum: 1920).\n        height : int\n            (Optional) Height of the image in pixels (Maximum: 1200).\n        watermark\n            (Optional) Whether or not the include the timestamps and the\n            Helioviewer.org logo in the image (Default=True).\n\n        Returns\n        -------\n        out : string\n            filepath to the PNG image\n\n        Examples\n        --------\n        >>> from sunpy.net.helioviewer import HelioviewerClient\n        >>> hv = HelioviewerClient()\n        >>> hv.download_png('2012/07/16 10:08:00', 2.4, \"[SDO,AIA,AIA,171,1,100]\", x0=0, y0=0, width=1024, height=1024)   # doctest: +SKIP\n        >>> hv.download_png('2012/07/16 10:08:00', 4.8, \"[SDO,AIA,AIA,171,1,100],[SOHO,LASCO,C2,white-light,1,100]\", x1=-2800, x2=2800, y1=-2800, y2=2800, directory='~/Desktop')   # doctest: +SKIP\n        \"\"\"\n        params = {\n            \"action\": \"takeScreenshot\",\n            \"date\": self._format_date(date),\n            \"imageScale\": image_scale,\n            \"layers\": layers,\n            \"display\": True\n        }\n        params.update(kwargs)\n\n        return self._get_file(params, directory, overwrite=overwrite)\n\n    def is_online(self):\n        \"\"\"Returns True if Helioviewer is online and available.\"\"\"\n        try:\n            self.get_data_sources()\n        except urllib.error.URLError:\n            return False\n\n        return True\n\n    def _get_json(self, params):\n        \"\"\"Returns a JSON result as a string\"\"\"\n        reader = codecs.getreader(\"utf-8\")\n        response = self._request(params)\n        return json.load(reader(response))\n\n    def _get_file(self, params, directory=None, overwrite=False):\n        \"\"\"Downloads a file and return the filepath to that file\"\"\"\n        # Query Helioviewer.org\n        if directory is None:\n            directory = sunpy.config.get('downloads', 'download_dir')\n        else:\n            directory = os.path.abspath(os.path.expanduser(directory))\n\n        response = self._request(params)\n        try:\n            filepath = download_fileobj(response, directory, overwrite=overwrite)\n        finally:\n            response.close()\n\n        return filepath\n\n    def _request(self, params):\n        \"\"\"Sends an API request and returns the result\n\n        Parameters\n        ----------\n        params : `dict`\n            Parameters to send\n\n        Returns\n        -------\n        out : result of request\n        \"\"\"\n        response = urllib.request.urlopen(\n            self._api, urllib.parse.urlencode(params).encode('utf-8'))\n\n        return response\n\n    def _format_date(self, date):\n        \"\"\"Formats a date for Helioviewer API requests\"\"\"\n        return parse_time(date).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + \"Z\"\n", "path": "sunpy/net/helioviewer.py"}], "after_files": [{"content": "\"\"\"\nThis module provides a wrapper around the Helioviewer API.\n\"\"\"\nfrom __future__ import absolute_import\n\n#pylint: disable=E1101,F0401,W0231\n\n__author__ = [\"Keith Hughitt\"]\n__email__ = \"keith.hughitt@nasa.gov\"\n\nimport os\nimport json\nimport codecs\nimport sunpy\nfrom sunpy.time import parse_time\nfrom sunpy.util.net import download_fileobj\n\nfrom sunpy.extern.six.moves import urllib\n\n__all__ = ['HelioviewerClient']\n\n\nclass HelioviewerClient(object):\n    \"\"\"Helioviewer.org Client\"\"\"\n    def __init__(self, url=\"http://legacy.helioviewer.org/api/\"):\n        \"\"\"\n        url : location of the Helioviewer API.  The default location points to\n            version 1 of the API.  Version 1 of the Helioviewer API is\n            currently planned to be supported until the end of April 2017.\n        \"\"\"\n        self._api = url\n\n    def get_data_sources(self, **kwargs):\n        \"\"\"\n        Returns a structured list of datasources available at helioviewer.org.\n        \"\"\"\n        params = {\"action\": \"getDataSources\"}\n        params.update(kwargs)\n\n        return self._get_json(params)\n\n    def get_closest_image(self, date, **kwargs):\n        \"\"\"Finds the closest image available for the specified source and date.\n\n        For more information on what types of requests are available and the\n        expected usage for the response, consult the Helioviewer API\n        documentation: http://legacy.helioviewer.org/api/docs/v1/ .\n\n        Parameters\n        ----------\n        date : `datetime.datetime`, `str`\n            A string or datetime object for the desired date of the image\n        observatory : string\n            (Optional) Observatory name\n        instrument : string\n            (Optional) instrument name\n        detector : string\n            (Optional) detector name\n        measurement : string\n            (Optional) measurement name\n        sourceId : int\n            (Optional) data source id\n\n        Returns\n        -------\n        out : `dict`\n            A dictionary containing meta-information for the closest image matched\n\n        Examples\n        --------\n        >>> from sunpy.net import HelioviewerClient\n\n        >>> client = HelioviewerClient()\n        >>> metadata = client.get_closest_image('2012/01/01', sourceId=11)\n        >>> print(metadata['date'])\n        2012-01-01 00:00:07\n        \"\"\"\n        params = {\n            \"action\": \"getClosestImage\",\n            \"date\": self._format_date(date)\n        }\n        params.update(kwargs)\n\n        response = self._get_json(params)\n\n        # Cast date string to DateTime\n        response['date'] = parse_time(response['date'])\n\n        return response\n\n    def download_jp2(self, date, directory=None, overwrite=False, **kwargs):\n        \"\"\"\n        Downloads the JPEG 2000 that most closely matches the specified time and\n        data source.\n\n        The data source may be specified either using it's sourceId from the\n        get_data_sources query, or a combination of observatory, instrument,\n        detector and measurement.\n\n        Parameters\n        ----------\n        date : `datetime.datetime`, string\n            A string or datetime object for the desired date of the image\n        directory : string\n            (Optional) Directory to download JPEG 2000 image to.\n        observatory : string\n            (Optional) Observatory name\n        instrument : string\n            (Optional) instrument name\n        detector : string\n            (Optional) detector name\n        measurement : string\n            (Optional) measurement name\n        sourceId : int\n            (Optional) data source id\n        jpip : bool\n            (Optional) Returns a JPIP URI if set to True\n\n        Returns\n        -------\n        out : string\n            Returns a filepath to the downloaded JPEG 2000 image or a URL if\n            the \"jpip\" parameter is set to True.\n\n        Examples\n        --------\n        >>> import sunpy.map\n        >>> from sunpy.net import helioviewer\n        >>> hv = helioviewer.HelioviewerClient()\n        >>> filepath = hv.download_jp2('2012/07/03 14:30:00', observatory='SDO', instrument='AIA', detector='AIA', measurement='171')   # doctest: +SKIP\n        >>> aia = sunpy.map.Map(filepath)   # doctest: +SKIP\n        >>> aia.peek()   # doctest: +SKIP\n\n        >>> data_sources = hv.get_data_sources()\n        >>> hv.download_jp2('2012/07/03 14:30:00', sourceId=data_sources['SOHO']['LASCO']['C2']['white-light']['sourceId'])   # doctest: +SKIP\n        \"\"\"\n        params = {\n            \"action\": \"getJP2Image\",\n            \"date\": self._format_date(date)\n        }\n        params.update(kwargs)\n\n        # JPIP URL response\n        if 'jpip' in kwargs:\n            return self._get_json(params)\n\n        return self._get_file(params, directory, overwrite=overwrite)\n\n    def download_png(self, date, image_scale, layers, directory=None,\n                     overwrite=False, **kwargs):\n        \"\"\"Downloads a PNG image using data from Helioviewer.org.\n\n        Returns a single image containing all layers/image types requested.\n        If an image is not available for the date requested the closest\n        available image is returned. The region to be included in the\n        image may be specified using either the top-left and bottom-right\n        coordinates in arc-seconds, or a center point in arc-seconds and a\n        width and height in pixels. See the Helioviewer.org API Coordinates\n        Appendix for more information about working with coordinates in\n        Helioviewer.org.\n\n        Parameters\n        ----------\n        date : `datetime.datetime`, string\n            A string or datetime object for the desired date of the image\n        image_scale : float\n            The zoom scale of the image. Default scales that can be used are\n            0.6, 1.2, 2.4, and so on, increasing or decreasing by a factor\n            of 2. The full-res scale of an AIA image is 0.6.\n        layers : string\n            Each layer string is comma-separated with these values, e.g.:\n            \"[sourceId,visible,opacity]\" or \"[obs,inst,det,meas,visible,opacity]\"\n            Multiple layer string are by commas: \"[layer1],[layer2],[layer3]\"\n        directory : string\n            (Optional)  Directory to download JPEG 2000 image to.\n        x1 : float\n            (Optional) The offset of the image's left boundary from the center\n            of the sun, in arcseconds.\n        y1 : float\n            (Optional) The offset of the image's top boundary from the center\n            of the sun, in arcseconds.\n        x2 : float\n            (Optional) The offset of the image's right boundary from the\n            center of the sun, in arcseconds.\n        y2 : float\n            (Optional) The offset of the image's bottom boundary from the\n            center of the sun, in arcseconds.\n        x0 : float\n            (Optional) The horizontal offset from the center of the Sun.\n        y0 : float\n            (Optional) The vertical offset from the center of the Sun.\n        width : int\n            (Optional) Width of the image in pixels (Maximum: 1920).\n        height : int\n            (Optional) Height of the image in pixels (Maximum: 1200).\n        watermark\n            (Optional) Whether or not the include the timestamps and the\n            Helioviewer.org logo in the image (Default=True).\n\n        Returns\n        -------\n        out : string\n            filepath to the PNG image\n\n        Examples\n        --------\n        >>> from sunpy.net.helioviewer import HelioviewerClient\n        >>> hv = HelioviewerClient()\n        >>> hv.download_png('2012/07/16 10:08:00', 2.4, \"[SDO,AIA,AIA,171,1,100]\", x0=0, y0=0, width=1024, height=1024)   # doctest: +SKIP\n        >>> hv.download_png('2012/07/16 10:08:00', 4.8, \"[SDO,AIA,AIA,171,1,100],[SOHO,LASCO,C2,white-light,1,100]\", x1=-2800, x2=2800, y1=-2800, y2=2800, directory='~/Desktop')   # doctest: +SKIP\n        \"\"\"\n        params = {\n            \"action\": \"takeScreenshot\",\n            \"date\": self._format_date(date),\n            \"imageScale\": image_scale,\n            \"layers\": layers,\n            \"display\": True\n        }\n        params.update(kwargs)\n\n        return self._get_file(params, directory, overwrite=overwrite)\n\n    def is_online(self):\n        \"\"\"Returns True if Helioviewer is online and available.\"\"\"\n        try:\n            self.get_data_sources()\n        except urllib.error.URLError:\n            return False\n\n        return True\n\n    def _get_json(self, params):\n        \"\"\"Returns a JSON result as a string\"\"\"\n        reader = codecs.getreader(\"utf-8\")\n        response = self._request(params)\n        return json.load(reader(response))\n\n    def _get_file(self, params, directory=None, overwrite=False):\n        \"\"\"Downloads a file and return the filepath to that file\"\"\"\n        # Query Helioviewer.org\n        if directory is None:\n            directory = sunpy.config.get('downloads', 'download_dir')\n        else:\n            directory = os.path.abspath(os.path.expanduser(directory))\n\n        response = self._request(params)\n        try:\n            filepath = download_fileobj(response, directory, overwrite=overwrite)\n        finally:\n            response.close()\n\n        return filepath\n\n    def _request(self, params):\n        \"\"\"Sends an API request and returns the result\n\n        Parameters\n        ----------\n        params : `dict`\n            Parameters to send\n\n        Returns\n        -------\n        out : result of request\n        \"\"\"\n        response = urllib.request.urlopen(\n            self._api, urllib.parse.urlencode(params).encode('utf-8'))\n\n        return response\n\n    def _format_date(self, date):\n        \"\"\"Formats a date for Helioviewer API requests\"\"\"\n        return parse_time(date).strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + \"Z\"\n", "path": "sunpy/net/helioviewer.py"}]}