001package org.hl7.fhir.utilities.npm;
002
003import java.io.ByteArrayInputStream;
004import java.io.FileNotFoundException;
005import java.io.IOException;
006import java.io.InputStream;
007import java.text.ParseException;
008import java.text.SimpleDateFormat;
009import java.time.Instant;
010import java.time.format.DateTimeParseException;
011import java.util.*;
012
013import javax.annotation.Nullable;
014
015import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
016import org.hl7.fhir.utilities.FileUtilities;
017import org.hl7.fhir.utilities.Utilities;
018import org.hl7.fhir.utilities.VersionUtilities;
019import org.hl7.fhir.utilities.http.HTTPAuthenticationMode;
020import org.hl7.fhir.utilities.http.HTTPResult;
021import org.hl7.fhir.utilities.http.ManagedWebAccess;
022import org.hl7.fhir.utilities.http.ManagedWebAccessor;
023import org.hl7.fhir.utilities.json.model.JsonArray;
024import org.hl7.fhir.utilities.json.model.JsonObject;
025import org.hl7.fhir.utilities.json.model.JsonProperty;
026import org.hl7.fhir.utilities.json.parser.JsonParser;
027
028public class PackageClient {
029
030  private PackageServer server;
031  private String address;
032
033
034  public PackageClient(PackageServer server) {
035    super();
036    this.server = server;
037    address = this.server.getUrl();
038  }
039
040  public boolean exists(String id, String ver) throws IOException {
041    List<PackageInfo> vl = getVersions(id);
042    for (PackageInfo pi : vl) {
043      if (ver == null || ver.equals(pi.getVersion())) {
044        return true;
045      }
046    }
047    return false;
048  }
049
050  public InputStream fetch(String id, String ver) throws IOException {
051    return fetchCached(getPackageTarballUrl(id, ver));
052  }
053
054  private String getPackageTarballUrl(String id, String ver) throws IOException {
055    if (server.getServerType() == PackageServer.PackageServerType.NPM) {
056      return getNpmServerTarballUrl(id, ver);
057    }
058    return Utilities.pathURL(address, id, ver);
059  }
060
061  private String getNpmServerTarballUrl(String id, String ver) throws IOException {
062    String packageDescriptorUrl = Utilities.pathURL(address, id, ver);
063    JsonObject json;
064
065      json = fetchJson(packageDescriptorUrl);
066      JsonObject dist = json.getJsonObject("dist");
067      return dist.getJsonString("tarball").asString();
068
069  }
070
071  public InputStream fetch(PackageInfo info) throws IOException {
072    return fetchCached(getPackageTarballUrl(info.getId(), info.getVersion()));
073  }
074
075  public InputStream fetchCached(String url) throws IOException, FileNotFoundException {
076    return fetchUrl(url, null);
077  }
078
079  public List<PackageInfo> getVersions(String id) throws IOException {
080    String url = Utilities.pathURL(address, id);
081    List<PackageInfo> res = new ArrayList<>();
082    JsonObject json;
083    try {
084      json = fetchJson(url);
085      JsonObject versions = json.getJsonObject("versions");
086      boolean hasDates = true;
087      if (versions != null) {
088        for (JsonProperty v : versions.getProperties()) {
089          JsonObject obj = versions.getJsonObject(v.getName());
090          Instant d = getInstantFromPackageDate(obj);
091          if (d == null) {
092            hasDates = false;
093          }
094          res.add(new PackageInfo(obj.asString("Name", "name"),
095            obj.asString("Version", "version"),
096            obj.asString("FhirVersion", "fhirVersion"),
097            obj.asString("Description", "description"),
098            obj.asString("url"),
099            obj.asString("canonical"),
100            address, d));
101        }
102      }
103      if (hasDates) {
104        Collections.sort(res, new PackageInfo.PackageInfoSorter(true));
105      } else {
106        Collections.sort(res, new PackageInfo.PackageInfoSorter(false));
107      }
108    } catch (Exception e) {
109      System.out.println("Error fetching "+url+": "+e.getMessage());
110    }
111    return res;    
112  }
113
114  @Nullable
115  private static Instant getInstantFromPackageDate(JsonObject obj) {
116    try {
117      return obj.hasString("date") ? obj.asDate("date") : null;
118    } catch (DateTimeParseException e) {
119      try {
120        return new SimpleDateFormat("yyyyMMddhhmmss").parse(obj.getJsonString("date").asString()).toInstant();
121      } catch (ParseException ex) {
122        // we tried to parse the date, but failed twice. We're just going to pretend we didn't get a date 
123        return null;    
124      }
125    }
126  }
127
128  public List<PackageInfo> search(String name, String canonical, String fhirVersion, boolean preRelease) throws IOException {
129    CommaSeparatedStringBuilder params = new CommaSeparatedStringBuilder("&");
130    if (!Utilities.noString(name)) {
131      params.append("name="+name);
132    }
133    if (!Utilities.noString(canonical)) {
134      params.append("pkgcanonical="+canonical);
135    }
136    if (!Utilities.noString(fhirVersion)) {
137      params.append("fhirversion="+fhirVersion);
138    }
139    if (preRelease) {
140      params.append("prerelease="+preRelease);
141    }
142    List<PackageInfo> res = new ArrayList<>();
143    try {
144      JsonArray json = fetchJsonArray(Utilities.pathURL(address, "catalog?")+params.toString());
145      boolean hasDates = true;
146      for (JsonObject obj : json.asJsonObjects()) {
147        Instant d = obj.has("date") ? obj.asDate("date") : null;
148        if (d == null) {
149          hasDates = false;
150        }
151        res.add(new PackageInfo(obj.asString("Name", "name"),
152          obj.asString("Version", "version"),
153          obj.asString("FhirVersion", "fhirVersion"),
154          obj.asString("Description", "description"),
155          obj.asString("url"),
156          obj.asString("canonical"),
157          address, d));
158      }
159      if (hasDates) {
160        Collections.sort(res, new PackageInfo.PackageInfoSorter(true));
161      } else {
162        Collections.sort(res, new PackageInfo.PackageInfoSorter(false));
163      }
164    } catch (IOException e1) {
165    }
166    return res;    
167  }  
168
169  public Date getNewPackages(Date lastCalled, List<PackageInfo> updates) {
170    return null;
171  }
172 
173  private InputStream fetchUrl(String source, String accept) throws IOException {
174    ManagedWebAccessor webAccessor = ManagedWebAccess.accessor(Arrays.asList("web"));
175    if (server.getAuthenticationMode() == HTTPAuthenticationMode.TOKEN) {
176      webAccessor.withToken(server.getToken());
177    } else if (server.getAuthenticationMode() == HTTPAuthenticationMode.BASIC) {
178      webAccessor.withBasicAuth(server.getUsername(), server.getPassword());
179    } else if (server.getAuthenticationMode() == HTTPAuthenticationMode.APIKEY) {
180      webAccessor.withApiKey(server.getApiKey());
181    }
182    HTTPResult res = webAccessor.get(source, accept);
183    res.checkThrowException();
184    return new ByteArrayInputStream(res.getContent());
185  }
186
187  private JsonObject fetchJson(String source) throws IOException {
188    String src = FileUtilities.streamToString(fetchUrl(source, "application/json"));
189    //System.out.println(src);
190    return JsonParser.parseObject(src);
191  }
192  
193  private JsonArray fetchJsonArray(String source) throws IOException {
194    String src = FileUtilities.streamToString(fetchUrl(source, "application/json"));
195    //System.out.println(src);
196    return (JsonArray) JsonParser.parse(src);
197  }
198
199  public String url(String id, String v) {
200    return Utilities.pathURL(address, id, v);
201  }
202
203  public String getLatestVersion(String id) throws IOException {
204    List<PackageInfo> list = getVersions(id);
205    if (list.isEmpty()) {
206      throw new IOException("Package not found: "+id);
207    } else {
208      String v = list.get(0).getVersion();
209      for (PackageInfo p : list) {
210        if (VersionUtilities.isThisOrLater(v, p.getVersion())) {
211          v = p.getVersion();
212        }
213      }
214      return v;
215    }
216  }
217  
218  public String getLatestVersion(String id, String specVersion) throws IOException {
219    List<PackageInfo> list = getVersions(id);
220    if (list.isEmpty()) {
221      throw new IOException("Package not found: "+id);
222    } else {
223      String v = null;
224      for (PackageInfo p : list) {
225        if (VersionUtilities.isMajMinOrLaterPatch(specVersion, p.getVersion())) {
226          v = p.getVersion();
227        }
228      }
229      return v;
230    }
231  }
232
233  protected PackageInfo getPackageInfoFromJSON(JsonObject o, String name, String canonical, String fhirVersion) {
234      String id = o.asString("npm-name");
235      String pname = o.asString("name");
236      String pcanonical = o.asString("canonical");
237      String description = o.asString("description");
238      Instant d = o.has("date") ? o.asDate("date") : null;
239      boolean ok = true;
240      if (ok && !Utilities.noString(name)) {
241        ok = (pname != null && pname.contains(name)) || (description != null && description.contains(name)) || (id != null && id.contains(name));
242      }
243      if (ok && !Utilities.noString(canonical)) {
244        ok = pcanonical.contains(canonical);
245      }
246      String version = null;
247      String fVersion = null;
248      String url = null;
249
250      if (ok) {
251        // if we can find something...
252        for (JsonObject e : o.getJsonObjects("editions")) {
253          if (fhirVersion == null || fhirVersion.equals(e.asString("fhir-version"))) {
254            String v = e.asString("ig-version");
255            if (version == null || VersionUtilities.isThisOrLater(version, v)) {
256              version = v;
257              fVersion = e.getJsonArray("fhir-version").get(0).asString();
258              url = e.asString("url");
259
260              String npmPackage = e.asString("package");
261              if (npmPackage != null && id == null) {
262                id = npmPackage.substring(0, npmPackage.indexOf("#"));
263              }
264            }
265          }
266        }
267      }
268      return new PackageInfo(id, version, fVersion, description, url, pcanonical, address, d);
269  }
270  
271  public List<PackageInfo> listFromRegistry(String name, String canonical, String fhirVersion) throws IOException {
272    List<PackageInfo> result = new ArrayList<>();
273    JsonObject packages = JsonParser.parseObjectFromUrl("https://fhir.github.io/ig-registry/fhir-ig-list.json?nocache=" + System.currentTimeMillis());
274    for (JsonObject o : packages.getJsonObjects("guides")) {
275      if (o.has("canonical")) {
276      final PackageInfo packageInfo = getPackageInfoFromJSON(o, name, canonical, fhirVersion);
277        if (packageInfo.getVersion() != null) {
278          result.add(packageInfo);
279        }
280      }
281    }
282    return result;
283  }
284
285  public void findDependents(Set<String> list, String id) {
286    CommaSeparatedStringBuilder params = new CommaSeparatedStringBuilder("&");
287    params.append("dependency="+id.replace("#", "|"));
288    try {
289      JsonArray json = fetchJsonArray(Utilities.pathURL(address, "catalog?")+params.toString());
290      for (JsonObject obj : json.asJsonObjects()) {
291        list.add(obj.asString("Name", "name"));
292      }
293    } catch (IOException e1) {
294    }
295  }
296  
297}