diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a6f89c2 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target/ \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..8fb0510 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Manos Paterakis + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..4a6b080 --- /dev/null +++ b/README.md @@ -0,0 +1,122 @@ +# Java-SteamGridDB +A Java wrapper for SteamGridDB's API + +### Installation + +[![](https://jitpack.io/v/mpaterakis/java-steamgriddb.svg)](https://jitpack.io/#mpaterakis/java-steamgriddb) + +## Getting Started +#### Get your API key +[You can generate an API key on the preferences page.](https://www.steamgriddb.com/profile/preferences) + +#### Require the library into your project. +```java +import com.SteamGridDB.*; +import com.SteamGridDB.Enums.*; +import com.SteamGridDB.Connection.*; +``` + +#### Initialize the SGDBConnectionManager using your API key and the API base uri +```java +SGDBConnectionManager.initialize("https://www.steamgriddb.com/api/v2", "myAuthKey"); +``` + +#### Search for a game: +```java +// Get an ArrayList of games that match the search term +var games = Search.searchGamesByName("cyberpunk"); + +// Get a JSONObject containing the response from the API [Can be converted to string using .toString()] +var gamesJson = Search.searchGamesByNameJSON("cyberpunk"); +``` + +#### Get a game object without searching: +```java +// Get a Game using a GameId +var game = Game.getGameByGameId(1234); + +// Get a Game using a SteamAppId +var game = Game.getGameBySteamAppId(567890); + +// Get a Game using its constructor +var game = new Game(567890, SGDBIdTypes.SteamAppId); +``` + +#### Do something with a game object: +```java +// Get a Game's Name +var gameName = game.getName(); + +// Get a Game's styles +var stylesArray = game.getStyles(); +``` + +#### Get some grids: +```java +// Get grids by game ID +var grid = Grid.getGridsByGameId(1234); + +// Get grids by Steam App Id +var grids = Grid.getGridsBySteamAppId(1234); + +// Alternatively, you can do it like this: +var grids = Grid.getGridsById(1234, SGDBIdTypes.GameId); +``` + +#### Filter the styles: +```java +// Create an SGDBStyles array +SGDBStyles styles[] = {SGDBStyles.Alternate, SGDBStyles.NoLogo}; + +// Same as before, but using the styles filter +var grid = Grid.getGridsByGameId(1234, styles); + +var grids = Grid.getGridsBySteamAppId(1234, styles); + +var grids = Grid.getGridsById(1234, SGDBIdTypes.GameId, styles); +``` + +#### Do something with a grid object: +```java +// Get the first Grid's score +var gridScore = grids.get(0).getScore(); + +// Get the same Grid's Author's username +var authorName = grids.get(0).getAuthor().getName(); +``` + +## Other methods +#### Vote on grids: +```java +// Upvote the first grid of the game with ID 1234 +var grid = Grid.getGridsByGameId(1234).get(0); +grid.upvote(); + +// Downvote the same grid +var grid = Grid.getGridsByGameId(1234).get(0); +grid.upvote(); + +// Alternatively, use the Grid's ID (80 in this case) to vote: +Grid.upvoteById(80); +Grid.downvoteById(80); +``` + +#### Upload a grid: +```java +// Upload a blurred grid to Half-Life 2 (2254) +Grid.upload(2254, SGDBStyles.Blurred, "path/of/image.img"); +``` + +#### Delete grids: +```java +// Delete a grid by ID +Grid.deleteByGridID(gameID); + +// Delete multiple grids by ID +var gameIDs = {123, 456}; +Grid.deleteByGridIDs(gameIDs); + +// Delete a Grid object +var grid = Grid.getGridsByGameId(1234).get(0); +grid.delete(); +``` diff --git a/nbactions.xml b/nbactions.xml new file mode 100644 index 0000000..6d9031e --- /dev/null +++ b/nbactions.xml @@ -0,0 +1,46 @@ + + + + run + + jar + + + process-classes + org.codehaus.mojo:exec-maven-plugin:1.5.0:exec + + + -classpath %classpath ${packageClassName} + java + + + + debug + + jar + + + process-classes + org.codehaus.mojo:exec-maven-plugin:1.5.0:exec + + + -agentlib:jdwp=transport=dt_socket,server=n,address=${jpda.address} -classpath %classpath ${packageClassName} + java + true + + + + profile + + jar + + + process-classes + org.codehaus.mojo:exec-maven-plugin:1.5.0:exec + + + -classpath %classpath ${packageClassName} + java + + + diff --git a/pom.xml b/pom.xml new file mode 100644 index 0000000..4e754d5 --- /dev/null +++ b/pom.xml @@ -0,0 +1,26 @@ + + + 4.0.0 + com.steamgriddb + java-steamgriddb + 1.0 + jar + + + org.json + json + 20180813 + + + + UTF-8 + 11 + 11 + + + + jitpack.io + https://jitpack.io + + + \ No newline at end of file diff --git a/src/main/java/com/steamgriddb/Author.java b/src/main/java/com/steamgriddb/Author.java new file mode 100644 index 0000000..ccdc289 --- /dev/null +++ b/src/main/java/com/steamgriddb/Author.java @@ -0,0 +1,58 @@ +package com.steamgriddb; + +/** + * Represents a Author as found on SteamGridDB.com + * + * @author mpaterakis + */ +public class Author { + + /* + * Fields + */ + private String name = ""; + private String steam64 = ""; + private String avatar = ""; + + /** + * Constructor for Author. + * + * @param name The Author's name + * @param steam64 The Author's Steam64 ID + * @param avatar The Author's avatar URL + */ + public Author(String name, String steam64, String avatar) { + this.name = name; + this.steam64 = steam64; + this.avatar = avatar; + } + + /** + * Get the Author's name. + * + * @return The Author's name + */ + public String getName() { + return name; + } + + /** + * Get the Author's Steam64 ID. + * + * @return The Author's Steam64 ID + */ + public String getSteam64() { + return steam64; + } + + /** + * Get the Author's avatar URL. + * + * @return The Author's avatar URL + */ + public String getAvatar() { + return avatar; + } + + +} diff --git a/src/main/java/com/steamgriddb/Connection/SGDBConnectionManager.java b/src/main/java/com/steamgriddb/Connection/SGDBConnectionManager.java new file mode 100644 index 0000000..49855c9 --- /dev/null +++ b/src/main/java/com/steamgriddb/Connection/SGDBConnectionManager.java @@ -0,0 +1,263 @@ +package com.steamgriddb.Connection; + +import java.io.IOException; +import java.math.BigInteger; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpResponse; +import java.net.http.HttpRequest; +import java.net.http.HttpRequest.BodyPublisher; +import java.net.http.HttpRequest.BodyPublishers; +import java.net.http.HttpResponse.BodyHandlers; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Map; +import java.util.Random; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.json.JSONObject; + +/** + * This class handles the connection to SGDB. + * + * @author mpaterakis + */ +public class SGDBConnectionManager { + + /* + * Fields + */ + private static String APIUri = "https://www.steamgriddb.com/API/v2/"; + private static String authKey = ""; + + /** + * Get a JSONObject from an API path. + * + * @param APICallPath The API path + * @return JSONObject containing the response (Or error code if the call fails) + */ + public static JSONObject getJSON(String APICallPath) { + int statusCode = 0; + + try { + HttpClient client = HttpClient.newBuilder().build(); + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(APIUri + APICallPath)) + .GET() + .setHeader("Authorization", "Bearer " + authKey) + .build(); + + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + statusCode = response.statusCode(); + + System.out.println(response.toString()); + + JSONObject json = new JSONObject(response.body().toString()); + + if (statusCode != 200) { + System.out.println("API Error! Status code: " + statusCode); + } + + return json; + } catch (IOException | InterruptedException ex) { + Logger.getLogger(SGDBConnectionManager.class.getName()).log(Level.SEVERE, null, ex); + } + + return new JSONObject("{ \"success\": \"false\", \"status\": " + statusCode + "}"); + } + + + /** + * Make a POST request. + * + * @param APICallPath The API path for the request + * @return A JSONOBject containing the response of the request + */ + public static JSONObject post(String APICallPath) { + int statusCode = 0; + + try { + HttpClient client = HttpClient.newBuilder().build(); + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(APIUri + APICallPath)) + .POST(BodyPublishers.ofString("")) + .setHeader("Authorization", "Bearer " + authKey) + .build(); + + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + statusCode = response.statusCode(); + + JSONObject json = new JSONObject(response.body().toString()); + + if (statusCode != 200) { + System.out.println("API Error! Status code: " + statusCode); + } + + return json; + } catch (IOException | InterruptedException ex) { + Logger.getLogger(SGDBConnectionManager.class.getName()).log(Level.SEVERE, null, ex); + } + + return new JSONObject("{ \"success\": \"false\", \"status\": " + statusCode + "}"); + } + + + /** + * Make a multipart POST request. + * + * @param APICallPath The API path for the request + * @param params The parameters for the Multipart post + * @return A JSONObject containing the response of the request + */ + public static JSONObject postMultipart(String APICallPath, Map params) { + int statusCode = 0; + + try { + String boundary = new BigInteger(256, new Random()).toString(); + HttpClient client = HttpClient.newBuilder().build(); + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(APIUri + APICallPath)) + .headers("Content-Type", "multipart/form-data;boundary=" + boundary, + "Authorization", "Bearer " + authKey) + .POST(ofMimeMultipartData(params, boundary)) + .build(); + + HttpResponse response = client.send(request, BodyHandlers.ofString()); + statusCode = response.statusCode(); + + JSONObject json = new JSONObject(response.body().toString()); + + if (statusCode != 200) { + System.out.println("API Error! Status code: " + statusCode + ", Error: " + json.getJSONArray("errors")); + } + + return json; + } catch (IOException | InterruptedException ex) { + Logger.getLogger(SGDBConnectionManager.class.getName()).log(Level.SEVERE, null, ex); + } + + return new JSONObject("{ \"success\": \"false\", \"status\": " + statusCode + "}"); + } + + /** + * Make a DELETE request. + * + * @param APICallPath The API path for the request + * @return A JSONObject containing the response of the request + */ + public static JSONObject delete(String APICallPath) { + int statusCode = 0; + + try { + HttpClient client = HttpClient.newBuilder().build(); + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(APIUri + APICallPath)) + .DELETE() + .setHeader("Authorization", "Bearer " + authKey) + .build(); + + HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + statusCode = response.statusCode(); + + JSONObject json = new JSONObject(response.body().toString()); + + if (statusCode != 200) { + System.out.println("API Error! Status code: " + statusCode); + } + + return json; + } catch (IOException | InterruptedException ex) { + Logger.getLogger(SGDBConnectionManager.class.getName()).log(Level.SEVERE, null, ex); + } + + return new JSONObject("{ \"success\": \"false\", \"status\": " + statusCode + "}"); + } + + /** + * Get the API base uri. + * + * @return The API base uri + */ + public static String getApiUri() { + return APIUri; + } + + /** + * Set the API base uri. + * + * @param APIUri The API base uri + */ + public static void setApiUri(String APIUri) { + SGDBConnectionManager.APIUri = APIUri; + } + + /** + * Get the API authorization key. + * + * @return The API authorization key + */ + public static String getAuthKey() { + return authKey; + } + + /** + * Set the API authorization key. + * + * @param authKey The API authorization key + */ + public static void setAuthKey(String authKey) { + SGDBConnectionManager.authKey = authKey; + } + + /** + * Initialize SGDBConnectionManager's values. + * + * @param APIUri The API base uri + * @param authKey The API authorization key + */ + public static void initialize(String APIUri, String authKey) { + if (APIUri.charAt(APIUri.length() - 1) != '/') { + APIUri += "/"; + } + SGDBConnectionManager.APIUri = APIUri; + SGDBConnectionManager.authKey = authKey; + } + + /** + * Make constructor private to give class a static nature + */ + private SGDBConnectionManager() { + } + + /** + * Create a multipart body. [Taken from https://golb.hplar.ch/2019/01/java-11-http-client.html]. + * + * @param data The data to be converted to multipart + * @param boundary A boundary String for the separator + * @return A multipart BodyPublisher + * @throws IOException + */ + private static BodyPublisher ofMimeMultipartData(Map data, String boundary) throws IOException { + var byteArrays = new ArrayList(); + byte[] separator = ("--" + boundary + "\r\nContent-Disposition: form-data; name=").getBytes(StandardCharsets.UTF_8); + for (Map.Entry entry : data.entrySet()) { + byteArrays.add(separator); + + if (entry.getValue() instanceof Path) { + var path = (Path) entry.getValue(); + String mimeType = Files.probeContentType(path); + byteArrays.add(("\"" + entry.getKey() + "\"; filename=\"" + path.getFileName() + + "\"\r\nContent-Type: " + mimeType + "\r\n\r\n").getBytes(StandardCharsets.UTF_8)); + byteArrays.add(Files.readAllBytes(path)); + byteArrays.add("\r\n".getBytes(StandardCharsets.UTF_8)); + } else { + byteArrays.add(("\"" + entry.getKey() + "\"\r\n\r\n" + entry.getValue() + "\r\n") + .getBytes(StandardCharsets.UTF_8)); + } + } + byteArrays.add(("--" + boundary + "--").getBytes(StandardCharsets.UTF_8)); + return BodyPublishers.ofByteArrays(byteArrays); + } +} diff --git a/src/main/java/com/steamgriddb/Enums/SGDBIdTypes.java b/src/main/java/com/steamgriddb/Enums/SGDBIdTypes.java new file mode 100644 index 0000000..377c586 --- /dev/null +++ b/src/main/java/com/steamgriddb/Enums/SGDBIdTypes.java @@ -0,0 +1,11 @@ +package com.steamgriddb.Enums; + +/** + * ENUM containing the types of IDs SGDB can use. + * + * @author mpaterakis + */ +public enum SGDBIdTypes { + SteamAppId, + GameId +} diff --git a/src/main/java/com/steamgriddb/Enums/SGDBStyles.java b/src/main/java/com/steamgriddb/Enums/SGDBStyles.java new file mode 100644 index 0000000..1e7e853 --- /dev/null +++ b/src/main/java/com/steamgriddb/Enums/SGDBStyles.java @@ -0,0 +1,13 @@ +package com.steamgriddb.Enums; + +/** + * ENUM containing the Styles SGDB can use. + * + * @author mpaterakis + */ +public enum SGDBStyles { + Alternate, + NoLogo, + Blurred, + Material +} diff --git a/src/main/java/com/steamgriddb/Game.java b/src/main/java/com/steamgriddb/Game.java new file mode 100644 index 0000000..7d13ccf --- /dev/null +++ b/src/main/java/com/steamgriddb/Game.java @@ -0,0 +1,118 @@ +package com.steamgriddb; + +import com.steamgriddb.Enums.SGDBIdTypes; +import com.steamgriddb.Connection.SGDBConnectionManager; +import java.util.ArrayList; +import org.json.JSONObject; +import org.json.JSONArray; + +/** + * Represents a Game as found on SteamGridDB.com + * + * @author mpaterakis + */ +public class Game { + + /* + * Fields + */ + private int id = -1; + private String name = ""; + private ArrayList types = new ArrayList<>(); + + /** + * Constructor for Game. + * + * @param id The id of the Game + * @param type The type of the given id + */ + public Game(int id, SGDBIdTypes type) { + JSONObject json = new JSONObject(); + + if (type == SGDBIdTypes.SteamAppId) { + json = SGDBConnectionManager.getJSON("games/steam/" + id); + } else if (type == SGDBIdTypes.GameId) { + json = SGDBConnectionManager.getJSON("games/id/" + id); + } + + if (json.getBoolean("success")) { + this.id = json.getJSONObject("data").getInt("id"); + this.name = json.getJSONObject("data").getString("name"); + JSONArray typesArray = json.getJSONObject("data").getJSONArray("types"); + for (int i = 0; i < typesArray.length(); i++) { + this.types.add(typesArray.get(i).toString()); + } + } + } + + /** + * Get a Game object from a SteamAppId. + * + * @param steamAppId The Game's SteamAppId + * @return A Game object + */ + public static Game getGameBySteamAppId(int steamAppId) { + Game game = new Game(steamAppId, SGDBIdTypes.SteamAppId); + return game; + } + + /** + * Get a JSONObject of a Game from a SteamAppId. + * + * @param steamAppId The Game's SteamAppId + * @return A JSONObject object with the Game's data + */ + public static JSONObject getGameJSONBySteamAppId(int steamAppId) { + JSONObject json = SGDBConnectionManager.getJSON("games/steam/" + steamAppId); + return json; + } + + /** + * Get a Game object from a GameId. + * + * @param gameId The Game's GameId + * @return A Game object + */ + public static Game getGameByGameId(int gameId) { + Game game = new Game(gameId, SGDBIdTypes.GameId); + return game; + } + + /** + * Get a JSONObject of a Game from a GameId. + * + * @param gameId The Game's GameId + * @return A JSONObject object with the Game's data + */ + public static JSONObject getGameJSONByGameId(int gameId) { + JSONObject json = SGDBConnectionManager.getJSON("games/id/" + gameId); + return json; + } + + /** + * Get the Game's id. + * + * @return id of the Game + */ + public int getId() { + return id; + } + + /** + * Get the Game's name. + * + * @return name of the Game + */ + public String getName() { + return name; + } + + /** + * Get the Game's types. + * + * @return types of the Game + */ + public ArrayList getTypes() { + return types; + } +} diff --git a/src/main/java/com/steamgriddb/Grid.java b/src/main/java/com/steamgriddb/Grid.java new file mode 100644 index 0000000..ebd881f --- /dev/null +++ b/src/main/java/com/steamgriddb/Grid.java @@ -0,0 +1,481 @@ +package com.steamgriddb; + +import com.steamgriddb.Enums.SGDBIdTypes; +import com.steamgriddb.Enums.SGDBStyles; +import com.steamgriddb.Connection.SGDBConnectionManager; +import java.io.File; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.Map; +import org.json.JSONArray; +import org.json.JSONObject; + +/** + * Represents a Grid as found on SteamGridDB.com + * + * @author mpaterakis + */ +public class Grid { + + /* + * Fields + */ + private int id = -1; + private double score = -1; + private String style = ""; + private String url = ""; + private String thumb = ""; + private ArrayList tags = new ArrayList<>(); + private Author author; + + /** + * Constructor for Grid. + * + * @param id The Grid ID + * @param score The Grid's Score + * @param style The Grid's Style + * @param url The Grid's URL + * @param thumb The Grid's Thumb URL + * @param tags The Grid's Tags + * @param author The Grid's Author + */ + public Grid(int id, double score, SGDBStyles style, String url, String thumb, ArrayList tags, Author author) { + switch (style) { + case Alternate: { + this.style = "alternate"; + break; + } + case NoLogo: { + this.style = "no_logo"; + break; + } + case Blurred: { + this.style = "blurred"; + break; + } + case Material: { + this.style = "material"; + break; + } + default: + break; + } + this.id = id; + this.score = score; + this.url = url; + this.thumb = thumb; + this.tags = tags; + this.author = author; + } + + /** + * Get Grids by ID and filter by styles. + * + * @param id The ID a Game uses + * @param idType The type of ID (SteamAppID or GameID) + * @param styles An array of styles for filtering the results + * @return An ArrayList of Grid objects + */ + public static ArrayList getGridsById(int id, SGDBIdTypes idType, SGDBStyles[] styles) { + ArrayList grids = new ArrayList<>(); + String apiUrl = ""; + String stylesStr = buildStylesString(styles); + + if (idType == SGDBIdTypes.GameId) { + apiUrl = "grids/game/"; + } else if (idType == SGDBIdTypes.SteamAppId) { + apiUrl = "grids/steam/"; + } + + JSONObject json = SGDBConnectionManager.getJSON(apiUrl + id + "?styles=" + stylesStr); + + if (json.getBoolean("success")) { + JSONArray jsonArray = json.getJSONArray("data"); + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject jsonGrid = jsonArray.getJSONObject(i); + JSONObject jsonAuthor = jsonGrid.getJSONObject("author"); + + JSONArray jsonTags = jsonGrid.getJSONArray("tags"); + + ArrayList tagStrings = new ArrayList<>(); + + for (int j = 0; j < jsonTags.length(); j++) { + tagStrings.add(jsonTags.get(i).toString()); + } + + Author authorObject = new Author(jsonAuthor.getString("name"), jsonAuthor.getString("steam64"), jsonAuthor.getString("avatar")); + + String styleString = jsonGrid.getString("style"); + SGDBStyles style = null; + switch (styleString) { + case "alternate": { + style = SGDBStyles.Alternate; + break; + } + case "no_logo": { + style = SGDBStyles.NoLogo; + break; + } + case "blurred": { + style = SGDBStyles.Blurred; + break; + } + case "material": { + style = SGDBStyles.Material; + break; + } + default: + break; + } + + Grid grid = new Grid(jsonGrid.getInt("id"), jsonGrid.getDouble("score"), style, + jsonGrid.getString("url"), jsonGrid.getString("thumb"), tagStrings, authorObject); + grids.add(grid); + } + } + + return grids; + } + + /** + * Get Grids by ID. + * + * @param id The ID a Game uses + * @param idType The type of ID (SteamAppID or GameID) + * @return An ArrayList of Grid objects + */ + public static ArrayList getGridsById(int id, SGDBIdTypes idType) { + ArrayList grids = new ArrayList<>(); + grids = getGridsById(id, idType, new SGDBStyles[0]); + return grids; + } + + /** + * Get Grids by SteamAppID. + * + * @param steamAppId The SteamAppID of a Game + * @param styles An array of SGDBStyles for filtering Grids + * @return An ArrayList of Grid objects + */ + public static ArrayList getGridsBySteamAppId(int steamAppId, SGDBStyles[] styles) { + ArrayList grids = new ArrayList<>(); + grids = getGridsById(steamAppId, SGDBIdTypes.SteamAppId, styles); + return grids; + } + + /** + * Get Grids by SteamAppID. + * + * @param steamAppId The SteamAppID of a Game + * @return An ArrayList of Grid objects + */ + public static ArrayList getGridsBySteamAppId(int steamAppId) { + ArrayList grids = new ArrayList<>(); + grids = getGridsById(steamAppId, SGDBIdTypes.SteamAppId); + return grids; + } + + /** + * Get Grids by GameID. + * + * @param gameId The GameID of a Game + * @param styles An array of SGDBStyles for filtering Grids + * @return An ArrayList of Grid objects + */ + public static ArrayList getGridsByGameId(int gameId, SGDBStyles[] styles) { + ArrayList grids = new ArrayList<>(); + grids = getGridsById(gameId, SGDBIdTypes.GameId, styles); + return grids; + } + + /** + * Get Grids by GameID. + * + * @param gameId The GameID of a Game + * @return An ArrayList of Grid objects + */ + public static ArrayList getGridsByGameId(int gameId) { + ArrayList grids = new ArrayList<>(); + grids = getGridsById(gameId, SGDBIdTypes.GameId); + return grids; + } + + /** + * Get a JSONObject of a Grids array from a SteamAppId. + * + * @param steamAppId A Game's SteamAppId + * @param styles An array of SGDBStyles for filtering Grids + * @return A JSONObject object with the Grid data + */ + public static JSONObject getGridJSONBySteamAppId(int steamAppId, SGDBStyles[] styles) { + String stylesStr = buildStylesString(styles); + JSONObject json = SGDBConnectionManager.getJSON("grids/steam/" + steamAppId + "?styles=" + stylesStr); + return json; + } + + /** + * Get a JSONObject of a Grids array from a SteamAppId. + * + * @param steamAppId A Game's SteamAppId + * @return A JSONObject object with the Grid data + */ + public static JSONObject getGridJSONBySteamAppId(int steamAppId) { + JSONObject json = SGDBConnectionManager.getJSON("grids/steam/" + steamAppId); + return json; + } + + /** + * Get a JSONObject of a Grids array from a GameId. + * + * @param gameId A Game's GameId + * @param styles An array of SGDBStyles for filtering Grids + * @return A JSONObject object with the Grid data + */ + public static JSONObject getGridJSONByGameId(int gameId, SGDBStyles[] styles) { + String stylesStr = buildStylesString(styles); + JSONObject json = SGDBConnectionManager.getJSON("grids/game/" + gameId + "?styles=" + stylesStr); + return json; + } + + /** + * Get a JSONObject of a Grids array from a GameId. + * + * @param gameId A Game's GameId + * @return A JSONObject object with the Grid data + */ + public static JSONObject getGridJSONByGameId(int gameId) { + JSONObject json = SGDBConnectionManager.getJSON("grids/game/" + gameId); + return json; + } + + /** + * Upload a Grid by entering its required data. + * + * @param gameId The GameID of a Game + * @param style The style of the Grid + * @param filePath The file path of an image + * @return True if the upload was successful, false if otherwise + */ + public static boolean uploadGrid(int gameId, SGDBStyles style, String filePath) { + File grid = new File(filePath); + + String styleStr = ""; + + switch (style) { + case Alternate: { + styleStr = "alternate"; + break; + } + case NoLogo: { + styleStr = "no_logo"; + break; + } + case Blurred: { + styleStr = "blurred"; + break; + } + case Material: { + styleStr = "material"; + break; + } + default: + break; + } + + Map params = new LinkedHashMap<>(); + params.put("game_id", gameId); + params.put("style", styleStr); + params.put("grid", grid.toPath()); + + JSONObject json = SGDBConnectionManager.postMultipart("grids", params); + + return json.getBoolean("success"); + } + + /** + * Vote for a Grid using its ID. + * + * @param vote The vote's value (True = Upvote, False = Downvote) + * @param gridID The Grid's ID + */ + public static void vote(boolean vote, int gridID) { + if (vote) { + upvoteById(gridID); + } else { + downvoteById(gridID); + } + } + + /** + * Vote for this Grid. + * + * @param vote The vote's value (True = Upvote, False = Downvote) + */ + public void vote(boolean vote) { + if (vote) { + upvote(); + } else { + downvote(); + } + } + + /** + * Upvote this Grid. + */ + public void upvote() { + SGDBConnectionManager.post("grids/vote/up/" + getId()); + } + + /** + * Downvote this Grid. + */ + public void downvote() { + SGDBConnectionManager.post("grids/vote/down/" + getId()); + } + + /** + * Upvote a Grid using its ID. + * + * @param gridId The Grid's ID + */ + public static void upvoteById(int gridId) { + SGDBConnectionManager.post("grids/vote/up/" + gridId); + } + + /** + * Downvote a Grid using its ID. + * + * @param gridId The Grid's ID + */ + public static void downvoteById(int gridId) { + SGDBConnectionManager.post("grids/vote/down/" + gridId); + } + + /** + * Delete this Grid. + */ + public void delete() { + SGDBConnectionManager.delete("grids/" + getId()); + } + + /** + * Delete a Grid using its ID. + * + * @param gridId The Grid's ID + */ + public static void deleteByGridID(int gridId) { + SGDBConnectionManager.delete("grids/" + gridId); + } + + /** + * Delete multiple Grids using an array of IDs. + * + * @param gridIds The Grid's ID + */ + public static void deleteByGridIDs(int[] gridIds) { + for (int i = 0; i < gridIds.length; i++) { + deleteByGridID(gridIds[i]); + } + } + + /** + * Get the Grid's ID. + * + * @return The Grid's ID + */ + public int getId() { + return id; + } + + /** + * Get the Grid's Score. + * + * @return The Grid's Score + */ + public double getScore() { + return score; + } + + /** + * Get the Grid's Style. + * + * @return The Grid's Style + */ + public String getStyle() { + return style; + } + + /** + * Get the Grid's URL. + * + * @return The Grid's URL + */ + public String getUrl() { + return url; + } + + /** + * Get the Grid's Thumb URL. + * + * @return The Grid's Thumb URL + */ + public String getThumb() { + return thumb; + } + + /** + * Get the Grid's Tags. + * + * @return The Grid's Tags + */ + public ArrayList getTags() { + return tags; + } + + /** + * Get the Grid's Author. + * + * @return The Grid's Author + */ + public Author getAuthor() { + return author; + } + + /** + * + */ + private static String buildStylesString(SGDBStyles[] styles) { + String stylesStr = ""; + + for (int i = 0; i < styles.length; i++) { + String currentStyle = ""; + switch (styles[i]) { + case Alternate: { + currentStyle = "alternate"; + break; + } + case NoLogo: { + currentStyle = "no_logo"; + break; + } + case Blurred: { + currentStyle = "blurred"; + break; + } + case Material: { + currentStyle = "material"; + break; + } + default: + break; + } + stylesStr += currentStyle; + if (i != styles.length - 1) { + stylesStr += ","; + } + } + + return stylesStr; + } + +} diff --git a/src/main/java/com/steamgriddb/Search.java b/src/main/java/com/steamgriddb/Search.java new file mode 100644 index 0000000..d39b58c --- /dev/null +++ b/src/main/java/com/steamgriddb/Search.java @@ -0,0 +1,57 @@ +package com.steamgriddb; + +import com.steamgriddb.Connection.SGDBConnectionManager; +import com.steamgriddb.Enums.SGDBIdTypes; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.logging.Level; +import java.util.logging.Logger; +import org.json.JSONArray; +import org.json.JSONObject; + +/** + * This class represents SGDB's Search API function. + * + * @author mpaterakis + */ +public class Search { + + /** + * Search for Games using a search term. + * + * @param searchTerm The search term to be used in the search + * @return An ArrayList of Game objects that the search yielded + */ + public static ArrayList searchGamesByName(String searchTerm) { + JSONObject json = new JSONObject(); + try { + json = SGDBConnectionManager.getJSON("search/autocomplete/" + URLEncoder.encode(searchTerm, "UTF-8")); + } catch (UnsupportedEncodingException ex) { + Logger.getLogger(Search.class.getName()).log(Level.SEVERE, null, ex); + } + + if (json.getBoolean("success")) { + ArrayList games = new ArrayList<>(); + JSONArray gamesArray = json.getJSONArray("data"); + for (int i = 0; i < gamesArray.length(); i++) { + games.add(new Game(gamesArray.getJSONObject(i).getInt("id"), SGDBIdTypes.GameId)); + } + return games; + } + + // If json is empty, return empty ArrayList + return new ArrayList<>(); + } + + /** + * Search for Games using a search term to get a raw JSONObject. + * + * @param searchTerm The search term to be used in the search + * @return A JSONObject that the search yielded + */ + public static JSONObject searchGamesByNameJSON(String searchTerm) { + JSONObject json = SGDBConnectionManager.getJSON("search/autocomplete/" + searchTerm); + return json; + } +}