forked from yannforget/landsatxplore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
earthexplorer.py
186 lines (164 loc) · 6.92 KB
/
earthexplorer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
"""Handle login and downloading from the EarthExplorer portal."""
import os
import re
import requests
from tqdm import tqdm
from landsatxplore_V2.api import API
from landsatxplore_V2.errors import EarthExplorerError
from landsatxplore_V2.util import guess_dataset, is_display_id
EE_URL = "https://earthexplorer.usgs.gov/"
EE_LOGIN_URL = "https://ers.cr.usgs.gov/login/"
EE_LOGOUT_URL = "https://earthexplorer.usgs.gov/logout"
EE_DOWNLOAD_URL = (
"https://earthexplorer.usgs.gov/download/{data_product_id}/{entity_id}/EE/"
)
# IDs of GeoTIFF data product for each dataset
DATA_PRODUCTS = {
"landsat_tm_c1": "5e83d08fd9932768",
"landsat_etm_c1": "5e83a507d6aaa3db",
"landsat_8_c1": "5e83d0b84df8d8c2",
"landsat_tm_c2_l1": "5e83d0a0f94d7d8d",
"landsat_etm_c2_l1": "5e83d0d0d2aaa488",
"landsat_ot_c2_l1": "5e81f14ff4f9941c",
"landsat_tm_c2_l2": "5e83d11933473426",
"landsat_etm_c2_l2": "5e83d12aada2e3c5",
"landsat_ot_c2_l2": "5e83d14f30ea90a9",
"sentinel_2a": "5e83a42c6eba8084",
}
DATA_PRODUCTS_II = {
"landsat_tm_c1": "5e83d08fd9932768",
"landsat_etm_c1": "5e83a507d6aaa3db",
"landsat_8_c1": "5e83d0b84df8d8c2",
"landsat_tm_c2_l1": "5e83d0a0f94d7d8d",
"landsat_etm_c2_l1": "5e83d0d08fec8a66",
"landsat_ot_c2_l1": "5e81f14f92acf9ef",
"landsat_tm_c2_l2": "5e83d11933473426",
"landsat_etm_c2_l2": "5e83d12aed0efa58",
"landsat_ot_c2_l2": "5e83d14fec7cae84",
"sentinel_2a": "5e83a42c6eba8084",
}
DATA_PRODUCTS_III = {
"landsat_tm_c1": "5e83d08fd9932768",
"landsat_etm_c1": "5e83a507d6aaa3db",
"landsat_8_c1": "5e83d0b84df8d8c2",
"landsat_tm_c2_l1": "63231219fdd8c4e5",
"landsat_etm_c2_l1": "5e83d0d08fec8a66",
"landsat_ot_c2_l1": "5e81f14f92acf9ef",
"landsat_tm_c2_l2": "632312ba6c0988ef",
"landsat_etm_c2_l2": "632311068b0935a8",
"landsat_ot_c2_l2": "632210d4770592cf",
"sentinel_2a": "5e83a42c6eba8084",
}
def _get_tokens(body):
"""Get `csrf_token` and `__ncforminfo`."""
# https://github.com/yannforget/landsatxplore/issues/76
csrf = re.findall(r'name="csrf" value="(.+?)"', body)[0]
# ncform = re.findall(r'name="__ncforminfo" value="(.+?)"', body)[0]
if not csrf:
raise EarthExplorerError("EE: login failed (csrf token not found).")
# if not ncform:
# raise EarthExplorerError("EE: login failed (ncforminfo not found).")
ncform = None
return csrf, ncform
class EarthExplorer(object):
"""Access Earth Explorer portal."""
def __init__(self, username, password):
"""Access Earth Explorer portal."""
self.session = requests.Session()
self.login(username, password)
self.api = API(username, password)
def logged_in(self):
"""Check if the log-in has been successfull based on session cookies."""
eros_sso = self.session.cookies.get("EROS_SSO_production_secure")
return bool(eros_sso)
def login(self, username, password):
"""Login to Earth Explorer."""
rsp = self.session.get(EE_LOGIN_URL)
# https://github.com/yannforget/landsatxplore/issues/76
# csrf, ncform = _get_tokens(rsp.text)
csrf = _get_tokens(rsp.text)
payload = {
"username": username,
"password": password,
"csrf": csrf,
# "__ncforminfo": ncform,
}
rsp = self.session.post(EE_LOGIN_URL, data=payload, allow_redirects=True)
if not self.logged_in():
raise EarthExplorerError("EE: login failed.")
def logout(self):
"""Log out from Earth Explorer."""
self.session.get(EE_LOGOUT_URL)
def _download(self, url, output_dir, timeout, chunk_size=1024, skip=False):
"""Download remote file given its URL."""
# Check availability of the requested product
# EarthExplorer should respond with JSON
with self.session.get(
url, allow_redirects=False, stream=True, timeout=timeout
) as r:
r.raise_for_status()
error_msg = r.json().get("errorMessage")
if error_msg:
raise EarthExplorerError(error_msg)
download_url = r.json().get("url")
try:
with self.session.get(
download_url, stream=True, allow_redirects=True, timeout=timeout
) as r:
file_size = int(r.headers.get("Content-Length"))
with tqdm(
total=file_size, unit_scale=True, unit="B", unit_divisor=1024
) as pbar:
local_filename = r.headers["Content-Disposition"].split("=")[-1]
local_filename = local_filename.replace('"', "")
local_filename = os.path.join(output_dir, local_filename)
if skip:
return local_filename
with open(local_filename, "wb") as f:
for chunk in r.iter_content(chunk_size=chunk_size):
if chunk:
f.write(chunk)
pbar.update(chunk_size)
except requests.exceptions.Timeout:
raise EarthExplorerError(
"Connection timeout after {} seconds.".format(timeout)
)
return local_filename
def download(self, identifier, output_dir, dataset=None, timeout=300, skip=False):
"""Download a Landsat scene.
Parameters
----------
identifier : str
Scene Entity ID or Display ID.
output_dir : str
Output directory. Automatically created if it does not exist.
dataset : str, optional
Dataset name. If not provided, automatically guessed from scene id.
timeout : int, optional
Connection timeout in seconds.
skip : bool, optional
Skip download, only returns the remote filename.
Returns
-------
filename : str
Path to downloaded file.
"""
os.makedirs(output_dir, exist_ok=True)
# https://github.com/yannforget/landsatxplore/issues/45#issuecomment-877012329
if not dataset:
dataset = guess_dataset(identifier)
if is_display_id(identifier):
entity_id = self.api.get_entity_id(identifier, dataset)
else:
entity_id = identifier
try:
url = EE_DOWNLOAD_URL.format(data_product_id=DATA_PRODUCTS[dataset], entity_id=entity_id)
filename = self._download(url, output_dir, timeout=timeout, skip=skip)
except:
try:
url = EE_DOWNLOAD_URL.format(data_product_id=DATA_PRODUCTS_II[dataset], entity_id=entity_id)
filename = self._download(url, output_dir, timeout=timeout, skip=skip)
except:
url = EE_DOWNLOAD_URL.format(data_product_id=DATA_PRODUCTS_III[dataset], entity_id=entity_id)
filename = self._download(url, output_dir, timeout=timeout, skip=skip)
return filename