/app/controllers/Application.java
Java | 2137 lines | 1763 code | 167 blank | 207 comment | 388 complexity | 742548c6cbdc889081855c023b02ae76 MD5 | raw file
- package controllers;
- import Persistence.MongoBase;
- import com.fasterxml.jackson.databind.JsonNode;
- import com.google.gson.JsonArray;
- import com.google.gson.JsonObject;
- import com.google.gson.JsonParser;
- import com.google.gson.JsonPrimitive;
- import com.mongodb.Mongo;
- import com.typesafe.plugin.MailerAPI;
- import com.typesafe.plugin.MailerPlugin;
- import models.*;
- import models.Notifications.Notification;
- import models.Notifications.Publication;
- import org.apache.poi.hssf.usermodel.HSSFSheet;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- import org.apache.poi.ss.usermodel.Cell;
- import org.apache.poi.ss.usermodel.Row;
- import org.bson.types.ObjectId;
- import play.Logger;
- import play.data.Form;
- import play.libs.Akka;
- import play.libs.F;
- import play.libs.WS;
- import play.libs.WS.WSRequestHolder;
- import play.mvc.Controller;
- import play.mvc.Result;
- import play.mvc.Security;
- import views.html.*;
- import javax.mail.*;
- import javax.mail.internet.InternetAddress;
- import javax.mail.internet.MimeMessage;
- import java.io.File;
- import java.io.FileInputStream;
- import java.util.*;
- import java.util.concurrent.Callable;
- import java.util.regex.Pattern;
- import static play.data.Form.form;
- public class Application extends Controller {
- private static final String FB_APP_ID = "583844725030243";
- private static final String FB_APP_SECRET = "fcc5fc20bb48f1a7da3f14ea83ebdec3";
- @Security.Authenticated(Secured.class)
- public static Result index() {
- if(session().get("role").equalsIgnoreCase("venue")){
- return redirect(
- routes.VenuePanel.blank()
- );
- }else if(session().get("role").equalsIgnoreCase("admin")){
- return redirect(
- routes.AdminPanel.blank()
- );
- }
- else{
- return ok(index.render(MongoBase.findListOfDishes(20), MongoBase.findListOfFeeds()));
- }
- }
- public static Result front() {
- return ok(front.render());
- }
- public static Result negocios() {
- return ok(negocios.render(form(ClientContact.class)));
- }
- /**
- * Display the paginated list of computers.
- *
- * @param page Current page number (starts from 0)
- * @param sortBy Column to be sorted
- * @param order Sort order (either asc or desc)
- * @param filter Filter applied on computer names
- */
- @Security.Authenticated(Secured.class)
- public static Result list(int page, String sortBy, String order, String filter) {
- return ok(
- list.render(
- Venues.page(page, 10, sortBy, order, filter),
- sortBy, order, filter
- )
- );
- }
- /**
- * Display the paginated list of computers.
- *
- * @param page Current page number (starts from 0)
- * @param sortBy Column to be sorted
- * @param order Sort order (either asc or desc)
- * @param filter Filter applied on computer names
- */
- @Security.Authenticated(Secured.class)
- public static Result dishesList(int page, String sortBy, String order, String filter) {
- return ok(
- dishList.render(
- Dishes.page(page, 10, sortBy, order, filter),
- sortBy, order, filter
- )
- );
- }
- /**
- * Display the paginated list of computers.
- *
- * @param page Current page number (starts from 0)
- * @param sortBy Column to be sorted
- * @param order Sort order (either asc or desc)
- */
- @Security.Authenticated(Secured.class)
- public static Result venueDishList(int page, String sortBy, String order, String filter) {
- Venue v=MongoBase.findVenueById(session().get("venueId"));
- return ok(
- venuedishes.render(v,
- Dishes.venuePage(page, 10, sortBy, order, session().get("venueId"),filter),
- sortBy, order, session().get("venueId"),filter
- )
- );
- }
- /**
- * Display the paginated list of computers.
- *
- * @param page Current page number (starts from 0)
- * @param sortBy Column to be sorted
- * @param order Sort order (either asc or desc)
- */
- @Security.Authenticated(Secured.class)
- public static Result venuePubList(int page, String sortBy, String order, String filter) {
- // Venue v=MongoBase.findVenueById(session().get("venueId"));
- return ok(
- venuepubs.render(
- Publications.venuePage(page, 10, sortBy, order, session().get("venueId"),filter),
- sortBy, order, session().get("venueId"),filter
- )
- );
- }
- @Security.Authenticated(Secured.class)
- public static Result dishesShowForProvince(String search, String location) {
- List<Dish> dishes = MongoBase.findListOfDishesByProvinceAndType(Dishes.cleanAndSplit(search), location);
- ;
- switch (dishes.size()) {
- case 1:
- return ok(dishShow.render(dishes.get(0), MongoBase.findListOfFeeds()));
- default:
- return ok(dishesShow.render(dishes, search, MongoBase.findListOfFeeds()));
- }
- }
- @Security.Authenticated(Secured.class)
- public static Result dishesShowForCity(String search, String location) {
- List<Dish> dishes = MongoBase.findListOfDishesByCityAndType(Dishes.cleanAndSplit(search), location);
- ;
- switch (dishes.size()) {
- case 1:
- return ok(dishShow.render(dishes.get(0), MongoBase.findListOfFeeds()));
- default:
- return ok(dishesShow.render(dishes, search, MongoBase.findListOfFeeds()));
- }
- }
- @Security.Authenticated(Secured.class)
- public static Result venuesShowForCity(String search, String location) {
- List<Venue> venues = MongoBase.findListOfVenuesForCity(search, location);
- ;
- switch (venues.size()) {
- case 1:
- return ok(venueShow.render(venues.get(0), MongoBase.findListOfDishesByVenueId(venues.get(0).oid.toString()), MongoBase.findListOfFeeds()));
- default:
- return ok(venuesShow.render(venues, search, MongoBase.findListOfFeeds()));
- }
- }
- @Security.Authenticated(Secured.class)
- public static Result venuesShowForProvince(String search, String location) {
- List<Venue> venues = MongoBase.findListOfVenuesForProvince(search, location);
- ;
- switch (venues.size()) {
- case 1:
- return ok(venueShow.render(venues.get(0), MongoBase.findListOfDishesByVenueId(venues.get(0).oid.toString()), MongoBase.findListOfFeeds()));
- default:
- return ok(venuesShow.render(venues, search, MongoBase.findListOfFeeds()));
- }
- }
- public static Result checkValidationCode() {
- JsonNode json = request().body().asJson();
- String code = json.findPath("registerCode").asText();
- if (code == null) {
- return badRequest("Missing parameter [code]. Where is my motherf***ing code!!");
- } else if (!MongoBase.checkValidationCode(code)) {
- return badRequest("No code, no user ");
- }
- return ok("CODIGO CORRECTO!");
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findVenueNameById(String venueId) {
- if (venueId == null) {
- return badRequest("Missing parameter [venueId].");
- }
- String venueName = MongoBase.findVenueNameById(venueId);
- if (venueName == null) {
- return badRequest("Bad Request");
- }
- return ok(venueName);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findVenueById(String venueId) {
- if (venueId == null) {
- return badRequest("Missing parameter [venueId].");
- }
- String venue = MongoBase.findVenueJsonById(venueId);
- if (venue == null) {
- return badRequest("Bad Request");
- }
- return ok(venue);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findVenueByIdPost() {
- JsonNode json = request().body().asJson();
- if(!json.has("venueId")){
- return badRequest("missing parameter [venueId]");
- }
- String venue = MongoBase.findVenueJsonById(json.findPath("venueId").asText());
- if (venue == null) {
- return badRequest("Bad Request");
- }
- return ok(venue);
- }
- public static Result okTio() {
- return ok();
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findReviewsByUserId() {
- JsonNode json = request().body().asJson();
- String userId = json.findPath("userId").textValue();
- if (userId == null) {
- return badRequest("Missing parameter [userId].");
- }
- String user = MongoBase.findReviewsByUserId(new ObjectId(userId));
- Logger.info(user);
- if (user == null) {
- return badRequest("Bad Request");
- }
- return ok(user);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findUserById() {
- JsonNode json = request().body().asJson();
- String userId = json.findPath("userId").asText();
- if (userId == null) {
- return badRequest("Missing parameter [userId].");
- }
- String user = MongoBase.findUserJSONById(userId);
- if (user == null) {
- return badRequest("Bad Request");
- }
- return ok(user);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findUsersByName() {
- JsonNode json = request().body().asJson();
- String name = json.findPath("name").asText();
- if (name == null) {
- return badRequest("Missing parameter [name].");
- }
- String user = MongoBase.findUsersByName(name);
- if (user == null) {
- return badRequest("Bad Request");
- }
- return ok(user);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findUsersFollowed() {
- JsonNode json = request().body().asJson();
- String userId = json.findPath("userId").asText();
- if (userId == null) {
- return badRequest("Missing parameter [useId].");
- }
- String user = MongoBase.findUsersFollowed(userId);
- if (user == null) {
- return badRequest("Bad Request");
- }
- return ok(user);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findUsersByIds() {
- JsonNode json = request().body().asJson();
- Iterator<JsonNode> i = json.findPath("usersIds").elements();
- if (i == null) {
- return badRequest("Missing parameter [usersIds]");
- }
- ArrayList<String> al = new ArrayList<String>();
- while (i.hasNext()) {
- al.add(i.next().asText());
- }
- String users = MongoBase.findUsersById(al);
- if (users == null) {
- return badRequest("Bad Request");
- }
- return ok(users);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result updateUser() {
- Logger.info("UPDATING USER? ");
- JsonNode object = request().body().asJson();
- Logger.info(object.toString());
- User user=new User();
- String oldPassword="";
- if (object.has("user")) {
- user.user = object.get("user").asText();
- }
- if (object.has("mail")) {
- user.mail = object.get("mail").asText();
- }
- if (object.has("_id")) {
- user._id = new ObjectId(object.get("_id").asText());
- }
- if (object.has("fbid")) {
- user.fbid = object.get("fbid").asText();
- }
- if (object.has("location")) {
- user.location = object.get("location").asText();
- }
- if (object.has("date")) {
- user.date = object.get("date").asText();
- }
- if (object.has("birthday")) {
- user.birthday = object.get("birthday").asText();
- }
- if (object.has("gender")) {
- user.gender = object.get("gender").asText();
- }
- if (object.has("phone")) {
- user.phone = object.get("phone").asText();
- }
- if (object.has("photoURL")) {
- user.photoURL=object.get("photoURL").asText();
- }
- if (object.has("password")) {
- user.password = object.get("password").asText();
- }
- if (object.has("oldPassword")) {
- oldPassword=object.get("oldPassword").asText();
- }
- String pass=MongoBase.retrievePassword(user.mail);
- Logger.info("mail: "+object.get("mail").asText());
- if(pass.equalsIgnoreCase(oldPassword)){
- if (MongoBase.updateUser(user)) {
- return ok("Edición de usuario completa");
- } else {
- Logger.info("Error editando.");
- return badRequest("Error editando el usuario");
- }
- }return badRequest("OldPassword incorrecto");
- }
- @Security.Authenticated(VenueSecured.class)
- public static Result updateClient() {
- Logger.info("UPDATING USER? ");
- JsonNode object = request().body().asJson();
- Logger.info(object.toString());
- Client client=new Client();
- String oldPassword="";
- if (object.has("mail")) {
- client.setMail(object.get("mail").asText());
- }
- if (object.has("phone")) {
- client.setPhone(object.get("phone").asText());
- }
- if (object.has("password")) {
- client.setPassword(object.get("password").asText());
- }
- if (object.has("oldPassword")) {
- oldPassword=object.get("oldPassword").asText();
- }
- String pass=MongoBase.retrievePassword(client.getMail());
- Logger.info("mail: "+object.get("mail").asText());
- if(pass.equalsIgnoreCase(oldPassword)){
- if (MongoBase.updateClient(client)) {
- return ok("Edición de cliente completa");
- } else {
- Logger.info("Error editando.");
- return badRequest("Error editando el cliente");
- }
- }return badRequest("OldPassword incorrecto");
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result updateUserWithoutPassword() {
- Logger.info("UPDATING USER? ");
- JsonNode object = request().body().asJson();
- Logger.info(object.toString());
- User user=new User();
- if (object.has("user")) {
- user.user = object.get("user").asText();
- }
- if (object.has("mail")) {
- user.mail = object.get("mail").asText();
- }
- if (object.has("_id")) {
- user._id = new ObjectId(object.get("_id").asText());
- }
- if (object.has("fbid")) {
- user.fbid = object.get("fbid").asText();
- }
- if (object.has("location")) {
- user.location = object.get("location").asText();
- }
- if (object.has("date")) {
- user.date = object.get("date").asText();
- }
- if (object.has("birthday")) {
- user.birthday = object.get("birthday").asText();
- }
- if (object.has("gender")) {
- user.gender = object.get("gender").asText();
- }
- if (object.has("phone")) {
- user.phone = object.get("phone").asText();
- }
- if (object.has("photoURL")) {
- user.photoURL=object.get("photoURL").asText();
- }
- if (MongoBase.updateUser(user)) {
- return ok("Edición de usuario completa");
- } else {
- Logger.info("Error editando.");
- return badRequest("Error editando el usuario");
- }
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result createVenueByName() {
- JsonNode json = request().body().asJson();
- String name = json.findPath("name").asText();
- if (name == null) {
- return badRequest("Missing parameter [name]. Y tal...");
- }
- String result = MongoBase.insertVenueByName(name);
- if (result == null) {
- return badRequest("Error al introducir la venue. Nombre repetido?");
- }
- return ok(result);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result createVenueByProvinceAndName() {
- JsonNode json = request().body().asJson();
- Venue venue=new Venue();
- if(json.has("insertedBy")){
- venue.insertedBy=json.findPath("insertedBy").asText();
- }
- if(json.has("province")){
- venue.address.province=json.findPath("province").asText();
- }
- else{
- return badRequest("Missing parameter [province]. Y tal...");
- }
- if (json.has("name")) {
- venue.name=json.findPath("name").asText();
- }
- else{
- return badRequest("Missing parameter [name]. Y tal...");
- }
- String result=MongoBase.insertVenueByProvinceAndName(venue);
- if ( result==null) {
- return badRequest("Error al introducir la venue.¿¿ Tal vez nombre repetido??");
- }
- return ok(result);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result createVenueOnLocation() {
- JsonNode json = request().body().asJson();
- String atributo = json.findPath("name").asText();
- if (atributo == null) {
- return badRequest("Missing parameter [name]. Y tal...");
- }
- Venue v = new Venue();
- v.name = atributo;
- v.coordinates[0] = (float) json.findPath("coordinates").get(0).doubleValue();
- v.coordinates[1] = (float) json.findPath("coordinates").get(1).doubleValue();
- atributo = json.findPath("street").asText();
- if (atributo != null) {
- v.address.street = atributo;
- }
- atributo = json.findPath("date").asText();
- if (atributo != null) {
- v.date = atributo;
- }
- atributo = json.findPath("insertedBy").asText();
- if (atributo != null) {
- v.insertedBy = atributo;
- }
- //no cojemos el streetNumber, hay lios con int/string
- /*atributo=json.findPath("streetNumber").asText();
- if(atributo!=null){
- v.address.streetNumber=atributo;
- }*/
- atributo = json.findPath("insertedBy").asText();
- if (atributo != null) {
- v.insertedBy = atributo;
- }
- atributo = json.findPath("city").asText();
- if (atributo != null) {
- v.address.city = atributo;
- }
- atributo = json.findPath("province").asText();
- if (atributo != null) {
- v.address.province = atributo;
- }
- atributo = json.findPath("postalCode").asText();
- if (atributo != null) {
- v.address.postalCode = atributo;
- }
- String retorno = MongoBase.insertVenueOnLocation(v);
- if (retorno == null) {
- return badRequest("Error al introducir la venue. Nombre repetido?");
- }
- return ok(retorno);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result createDishByNameAndVenueId() {
- Dish d = new Dish();
- JsonNode json = request().body().asJson();
- String name = json.findPath("name").asText();
- String venueId = json.findPath("venueId").asText();
- if (name == null || venueId == null) {
- return badRequest("Missing parameter [name]. Y tal...");
- }
- d.name = name;
- d.venueId = new ObjectId(venueId);
- String atributo = json.findPath("date").asText();
- if (atributo != null) {
- d.date = atributo;
- }
- atributo = json.findPath("insertedBy").asText();
- if (atributo != null) {
- d.insertedBy = atributo;
- }
- d.photoURL = "http://toptasting.s3.amazonaws.com/sinImagenDish.png";
- String dishId = MongoBase.insertDish(d);
- if (dishId == null) {
- return badRequest("Error al introducir el dish.");
- }
- return ok(dishId);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result createDish() {
- Dish d = new Dish();
- JsonNode json = request().body().asJson();
- String name = json.findPath("name").asText();
- String venueId = json.findPath("venueId").asText();
- if (name == null || venueId == null) {
- return badRequest("Missing parameter [name]. Y tal...");
- }
- if(json.hasNonNull("venueName")){
- d.venueName=json.findPath("venueName").asText();
- }
- if(json.hasNonNull("city")){
- d.city=json.findPath("city").asText();
- }
- if(json.hasNonNull("province")){
- d.province=json.findPath("province").asText();
- }
- if(json.hasNonNull("coordinates")){
- double[] coor = new double[2];
- if(json.findPath("coordinates").hasNonNull(0)){
- coor[0] = (float) json.findPath("coordinates").get(0).doubleValue();
- }
- if(json.findPath("coordinates").hasNonNull(1)){
- coor[1] = (float)json.findPath("coordinates").get(1).doubleValue();
- }
- d.coordinates=coor;
- }
- d.name = name;
- d.venueId = new ObjectId(venueId);
- String atributo = json.findPath("date").asText();
- if (atributo != null) {
- d.date = atributo;
- }
- atributo = json.findPath("insertedBy").asText();
- if (atributo != null) {
- d.insertedBy = atributo;
- }
- d.photoURL = "http://toptasting.s3.amazonaws.com/sinImagenDish.png";
- String dishId = MongoBase.insertDish(d);
- if (dishId == null) {
- return badRequest("Error al introducir el dish.");
- }
- return ok(dishId);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findDishes() {
- JsonNode json = request().body().asJson();
- String searchText = json.findPath("search").asText();
- if (searchText == null) {
- return badRequest("Missing search value");
- }
- String retorno = MongoBase.findDishes(searchText);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findDishesByType() {
- JsonNode json = request().body().asJson();
- Iterator<JsonNode> i = json.findPath("search").elements();
- if (i == null) {
- return badRequest("Missing search value");
- }
- ArrayList<String> al = new ArrayList<String>();
- while (i.hasNext()) {
- al.add(i.next().asText());
- }
- String retorno = MongoBase.findDishesByType(al);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findDishesByVenueId() {
- JsonNode json = request().body().asJson();
- String venueId = json.findPath("venueId").asText();
- if (venueId == null) {
- return badRequest("Missing parameter [venueId]");
- }
- String retorno = MongoBase.findDishesByVenueId(venueId);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- Logger.info("Solicitado FindDishesByVenueId");
- return ok(retorno);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findPublicationsByVenueId() {
- JsonNode json = request().body().asJson();
- String venueId = json.findPath("venueId").asText();
- if (venueId == null) {
- return badRequest("Missing parameter [venueId]");
- }
- String retorno = MongoBase.findPublicationsByVenueId(venueId);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- Logger.info("Solicitado FindPublicationsByVenueId");
- return ok(retorno);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findDrafts() {
- JsonNode json = request().body().asJson();
- String userId = json.findPath("userId").asText();
- Logger.info("Buscando drafts para el userId "+userId);
- if (userId == null) {
- Logger.info("Se trató de buscar drafts sin user ID");
- return badRequest("Missing parameter [userId].");
- }
- String drafts = MongoBase.findDrafts(new ObjectId(userId));
- if (drafts == null) {
- Logger.info("Ha habido un error buscando drafts");
- return badRequest("Bad Request");
- }
- Logger.info(drafts);
- return ok(drafts);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findFavVenuesByUserId() {
- JsonNode json = request().body().asJson();
- String userId = json.findPath("userId").asText();
- if (userId == null) {
- Logger.info("Se trató de buscar drafts sin user ID");
- return badRequest("Missing parameter [userId].");
- }
- String venues = MongoBase.findFavVenuesByUserId(userId);
- if (venues == null) {
- Logger.info("Ha habido un error buscando venues favoritas");
- return badRequest("Bad Request");
- }
- return ok(venues);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findFavDishesByUserId() {
- JsonNode json = request().body().asJson();
- String userId = json.findPath("userId").asText();
- if (userId == null) {
- Logger.info("Se trató de buscar platos sin user ID");
- return badRequest("Missing parameter [userId].");
- }
- String venues = MongoBase.findFavDishesByUserId(userId);
- if (venues == null) {
- Logger.info("Ha habido un error buscando platos favoritas");
- return badRequest("Bad Request");
- }
- return ok(venues);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findFavPublicationsByUserId() {
- JsonNode json = request().body().asJson();
- String userId = json.findPath("userId").asText();
- if (userId == null) {
- Logger.info("Se trató de buscar publicaciones sin user ID");
- return badRequest("Missing parameter [userId].");
- }
- String venues = MongoBase.findFavPublicationsByUserId(userId);
- if (venues == null) {
- Logger.info("Ha habido un error buscando publicaciones favoritas");
- return badRequest("Bad Request");
- }
- Logger.info("VENUE PUBLICATIONS: "+venues);
- return ok(venues);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findDishWithId(String dishId) {
- if (dishId == null) {
- return badRequest("Missing parameter [dishId].");
- }
- String dish = MongoBase.findDishJSONById(dishId);
- if (dish == null) {
- return badRequest("Bad Request");
- }
- return ok(dish);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findDishById() {
- JsonNode json = request().body().asJson();
- String dishId;
- if(json.has("dishId")){
- dishId = json.findPath("dishId").asText();
- }else{
- return badRequest("Faltan parámetros [dishId]");
- }
- String dish = MongoBase.findDishJSONById(dishId);
- if (dish == null) {
- return badRequest("Bad Request");
- }
- return ok(dish);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findNearbyVenues() {
- JsonNode json = request().body().asJson();
- float lat = (float) json.findPath("coordinates").get(0).doubleValue();
- float lon = (float) json.findPath("coordinates").get(1).doubleValue();
- double dis = json.findPath("dis").doubleValue();
- String retorno = MongoBase.findNearbyVenues(lat, lon, dis);
- Logger.info("dis: " + dis + " lat:" + lat + " lon:" + lon);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findNearbyVenuesByName() {
- JsonNode json = request().body().asJson();
- float lat = (float) json.findPath("coordinates").get(0).doubleValue();
- float lon = (float) json.findPath("coordinates").get(1).doubleValue();
- double dis = json.findPath("dis").doubleValue();
- String search = json.findPath("search").asText();
- String retorno = MongoBase.findNearbyVenuesByName(lat, lon, dis, search);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findVenuesByProvince() {
- JsonNode json = request().body().asJson();
- String location = json.findPath("location").asText();
- String retorno = MongoBase.findVenuesByProvince(location);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findVenuesByProvinceAndName() {
- JsonNode json = request().body().asJson();
- String location = json.findPath("location").asText();
- String search = json.findPath("search").asText();
- String retorno = MongoBase.findVenuesByProvinceAndName(location, search);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- public static Result findVenuesByCity() {
- JsonNode json = request().body().asJson();
- System.out.println("buscando venues por ciudad: "+json);
- String location = json.findPath("location").asText();
- String retorno = MongoBase.findVenuesByCity(location);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- public static Result findVenuesByCityAndName() {
- JsonNode json = request().body().asJson();
- String location = json.findPath("location").asText();
- String search = json.findPath("search").asText();
- String retorno = MongoBase.findVenuesByCityAndName(location, search);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findVenuesById() {
- JsonNode json = request().body().asJson();
- List<String> venueIds = json.findValuesAsText("venueIds");
- String retorno = MongoBase.findVenuesById(venueIds);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findNearbyDishesByType() {
- JsonNode json = request().body().asJson();
- float[] coor = new float[2];
- System.out.println("json recibido "+json);
- coor[0] = (float) json.findPath("coordinates").get(0).doubleValue();
- coor[1] = (float) json.findPath("coordinates").get(1).doubleValue();
- double dis = json.findPath("dis").doubleValue();
- Iterator<JsonNode> i = json.findPath("search").elements();
- Logger.info("dis: " + dis + " lat:" + coor[0] + " lon:" + coor[1]);
- if (i == null) {
- return badRequest("Missing search value");
- }
- ArrayList<String> al = new ArrayList<String>();
- while (i.hasNext()) {
- al.add(i.next().asText());
- }
- String retorno = MongoBase.findNearbyDishesByType(coor, dis, al);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findDishesByCityAndType() {
- JsonNode json = request().body().asJson();
- String location = json.findPath("location").asText();
- Iterator<JsonNode> i = json.findPath("search").elements();
- if (i == null) {
- return badRequest("Missing search value");
- }
- ArrayList<String> al = new ArrayList<String>();
- while (i.hasNext()) {
- al.add(i.next().asText());
- }
- String retorno = MongoBase.findDishesByCityAndType(location, al);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findDishesByProvinceAndType() {
- JsonNode json = request().body().asJson();
- String location = json.findPath("location").asText();
- Iterator<JsonNode> i = json.findPath("search").elements();
- if (i == null) {
- return badRequest("Missing search value");
- }
- ArrayList<String> al = new ArrayList<String>();
- while (i.hasNext()) {
- al.add(i.next().asText());
- }
- String retorno = MongoBase.findDishesByProvinceAndType(location, al);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- public static Result findNearbyDishes() {
- JsonNode json = request().body().asJson();
- Logger.info(json.toString());
- float[] coor = new float[2];
- coor[0] = (float) json.findPath("coordinates").get(0).doubleValue();
- coor[1] = (float) json.findPath("coordinates").get(1).doubleValue();
- double dis = json.findPath("dis").doubleValue();
- Logger.info("dis: " + dis + " lat:" + coor[0] + "lon:" + coor[1]);
- String retorno = MongoBase.findNearbyDishes(coor, dis);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findDishesByCity() {
- JsonNode json = request().body().asJson();
- String location = json.findPath("location").asText();
- String retorno = MongoBase.findDishesByCity(location);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findDishesByProvince() {
- JsonNode json = request().body().asJson();
- String location = json.findPath("location").asText();
- String retorno = MongoBase.findDishesByProvince(location);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- @Security.Authenticated(AdminSecured.class)
- public static Result consolidate() {
- MongoBase.consolidate();
- flash("success", "Consolidado");
- return redirect(
- routes.AdminPanel.blank()
- );
- }
- public static Result makeSearchNames() {
- MongoBase.makeSearchNames();
- flash("success", "Consolidado");
- return redirect(
- routes.AdminPanel.blank()
- );
- }
- @Security.Authenticated(AdminSecured.class)
- public static Result sendGCMMessage() {
- Publication pub=new Publication();
- pub.setLongDescription(" Lorem ipsum dolor sit amet");
- pub.setInterests(Arrays.asList(new String[]{"jornadas", "gochu"}));
- pub.setVenueId("522ecb6003647294e95cfe46");
- pub.setTitle("Pelazo abre en la pola");
- pub.setVenueLocation("pola de lena");
- MongoBase.createPublication(pub);
- return ok();
- }
- @Security.Authenticated(AdminSecured.class)
- public static Result readXML() {
- /* final int NAME=0;
- final int ADDRESS=1;
- final int CITY=2;
- final int POSTAL_CODE=4;
- final int BAJA=9;
- final int SUB_ACTIVITY=12;
- try
- {
- FileInputStream file = new FileInputStream(new File("/Users/marcosflorezsierra/Downloads/Establecimientos.xls"));
- //Create Workbook instance holding reference to .xlsx file
- HSSFWorkbook workbook = new HSSFWorkbook(file);
- //Get first/desired sheet from the workbook
- HSSFSheet sheet = workbook.getSheetAt(0);
- //Iterate through each rows one by one
- Iterator<Row> rowIterator = sheet.iterator();
- Venue venue;
- while (rowIterator.hasNext())
- {
- Row row = rowIterator.next();
- if(row.getCell(BAJA).getStringCellValue()!=null&&row.getCell(BAJA).getStringCellValue().length()>0){
- venue=new Venue();
- if(row.getCell(CITY).getStringCellValue().length()<1){
- venue.address.city=row.getCell(CITY+1).getStringCellValue();
- }else{
- venue.address.city=row.getCell(CITY).getStringCellValue();
- }
- venue.address.street=row.getCell(ADDRESS).getStringCellValue().toLowerCase();
- venue.address.postalCode=row.getCell(POSTAL_CODE).getStringCellValue();
- venue.address.province="Asturias";
- venue.name=row.getCell(NAME).getStringCellValue();
- if(venue.name.contains(", ")){
- String partes[]=venue.name.split(", ");
- venue.name=partes[1]+" "+partes[0];
- }else if(venue.name.contains(" ,")){
- String partes[]=venue.name.split(" ,");
- venue.name=partes[1]+" "+partes[0];
- }
- venue.name=venue.name.toLowerCase();
- venue.types.add("restaurante");
- String subActivity=row.getCell(SUB_ACTIVITY).getStringCellValue();
- if(subActivity!=null&&subActivity.length()>0){
- venue.types.add(subActivity.toLowerCase());
- }
- System.out.println(venue);
- }
- }
- file.close();
- }
- catch (Exception e)
- {
- e.printStackTrace();
- }
- */
- MongoBase.insertVenuesXML();
- return ok();
- }
- /*
- public static F.Promise<Result> sendGCMMessage() {
- JsonNode responseJson;
- final JsonNode json = request().body().asJson();
- String mail = json.findPath("mail").asText();
- JsonObject parameters=new JsonObject();
- JsonArray direcciones=new JsonArray();
- JsonObject data=new JsonObject();
- data.add("mensaje",new JsonPrimitive("yes muy malu al DOTA2"));
- direcciones.add(new JsonPrimitive("pepito"));
- parameters.add("registration_ids",direcciones);
- String token = json.findPath("userToken").asText();
- String auth = "AIzaSyD_v66gszhbLwY0iBGCi37Tsb467ruzs0o";
- WSRequestHolder messageRequest = WS.url("https://android.googleapis.com/gcm/send").setAuth("key",auth).setContentType("application/json");
- F.Promise<Result> resultado = messageRequest.post(parameters.getAsString()).map(
- new F.Function<WS.Response, Result>() {
- @Override
- public Result apply(WS.Response response) throws Throwable {
- switch(response.getStatus()){
- case 200: Logger.info("GCM messages correctos");
- flash("success", "Envíado!");
- return redirect(
- routes.AdminPanel.blank()
- );
- case 400:
- flash("error", "Mal JSON");
- return redirect(
- routes.AdminPanel.blank()
- );
- case 401:
- flash("error", "Mala Autenticación!");
- return redirect(
- routes.AdminPanel.blank()
- );
- default: flash("error", "ROMPISTE GOOGLE!!!! BOOOM!");
- return redirect(
- routes.AdminPanel.blank()
- );
- }
- }
- });
- return resultado;
- }
- */
- @Security.Authenticated(AdminSecured.class)
- public static Result corregirTipos() {
- MongoBase.correct();
- flash("success", "Corregidos");
- return redirect(
- routes.AdminPanel.blank()
- );
- }
- @Security.Authenticated(AdminSecured.class)
- public static Result recalculatePoints() {
- MongoBase.recalculatePoints();
- flash("success", "Recalculado");
- return redirect(
- routes.AdminPanel.blank()
- );
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findVenues() {
- JsonNode json = request().body().asJson();
- String searchText = json.findPath("search").asText();
- if (searchText == null) {
- return badRequest("Missing search value");
- }
- String retorno = MongoBase.findVenues(searchText);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- @Security.Authenticated(Secured.class)
- public static Result findMoreVenues() {
- JsonNode json = request().body().asJson();
- String searchText = json.findPath("search").asText();
- String attempt = json.findPath("attempt").asText();
- if (searchText == null) {
- return badRequest("Missing search value");
- }
- String retorno = MongoBase.findVenues(searchText);
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- @Security.Authenticated(Secured.class)
- public static Result addGcmId() {
- JsonNode json = request().body().asJson();
- String gcmId=null;
- String userId=null;
- if(json.has("gcmId")){
- gcmId = json.findPath("gcmId").asText();
- }else{
- return badRequest("Faltan parámetros [gcmId]");
- }
- if(json.has("userId")){
- userId = json.findPath("userId").asText();
- }else{
- return badRequest("Faltan parámetros [userId]");
- }
- String retorno = MongoBase.addGcmId(userId, gcmId);
- if (retorno != null) {
- return badRequest("Error añadiendo el gcmId");
- }
- return ok();
- }
- @Security.Authenticated(Secured.class)
- public static Result addUserFollower() {
- JsonNode json = request().body().asJson();
- String followerId=null;
- String followedId=null;
- String followerName=null;
- String followedName=null;
- if(json.has("followerId")){
- followerId = json.findPath("followerId").asText();
- }else{
- return badRequest("Faltan parámetros [followerId]");
- }
- if(json.has("followerName")){
- followerName = json.findPath("followerName").asText();
- }else{
- return badRequest("Faltan parámetros [followerName]");
- }
- if(json.has("followedId")){
- followedId = json.findPath("followedId").asText();
- }else{
- return badRequest("Faltan parámetros [followedId]");
- }
- if(json.has("followedName")){
- followedName = json.findPath("followedName").asText();
- }else{
- return badRequest("Faltan parámetros [followedName]");
- }
- String retorno = MongoBase.addUserFollower(followerId, followerName,followedId,followedName);
- if (retorno != null) {
- return badRequest("Error añadiendo follower");
- }
- return ok();
- }
- @Security.Authenticated(Secured.class)
- public static Result removeUserFollower() {
- JsonNode json = request().body().asJson();
- String followerId=null;
- String followedId=null;
- if(json.has("followerId")){
- followerId = json.findPath("followerId").asText();
- }else{
- return badRequest("Faltan parámetros [followerId]");
- }
- if(json.has("followedId")){
- followedId = json.findPath("followedId").asText();
- }else{
- return badRequest("Faltan parámetros [followedId]");
- }
- String retorno = MongoBase.removeUserFollower(followerId, followedId);
- if (retorno != null) {
- return badRequest("Error añadiendo follower");
- }
- return ok();
- }
- @Security.Authenticated(Secured.class)
- public static Result addVenueFollower() {
- JsonNode json = request().body().asJson();
- String followerName=null;
- String venueId=null;
- String venueName=null;
- String followerId=null;
- if(json.has("followerName")){
- followerName = json.findPath("followerName").asText();
- }else{
- return badRequest("Faltan parámetros [followerName]");
- }
- if(json.has("followerId")){
- followerId = json.findPath("followerId").asText();
- }
- else{
- return badRequest("Faltan parámetros [followerId]");
- }
- if(json.has("venueId")){
- venueId = json.findPath("venueId").asText();
- }else{
- return badRequest("Faltan parámetros [venueId]");
- }
- if(json.has("venueName")){
- venueName = json.findPath("venueName").asText();
- }else{
- return badRequest("Faltan parámetros [venueName]");
- }
- String retorno = MongoBase.addVenueFollower(followerId,followerName,venueId, venueName);
- if (retorno != null) {
- return badRequest("Error añadiendo follower");
- }
- return ok();
- }
- @Security.Authenticated(Secured.class)
- public static Result removeVenueFollower() {
- JsonNode json = request().body().asJson();
- String venueId=null;
- String followerId=null;
- if(json.has("followerId")){
- followerId = json.findPath("followerId").asText();
- }
- else{
- return badRequest("Faltan parámetros [followerId]");
- }
- if(json.has("venueId")){
- venueId = json.findPath("venueId").asText();
- }else{
- return badRequest("Faltan parámetros [venueId]");
- }
- String retorno = MongoBase.removeVenueFollower(followerId, venueId);
- if (retorno != null) {
- return badRequest("Error eliminando follower");
- }
- return ok();
- }
- @Security.Authenticated(Secured.class)
- public static Result addInterestFollower() {
- JsonNode json = request().body().asJson();
- String followerId=null;
- String followerName=null;
- String interestName=null;
- if(json.has("followerId")){
- followerId = json.findPath("followerId").asText();
- }else{
- return badRequest("Faltan parámetros [followerId]");
- }
- if(json.has("followerName")){
- followerName = json.findPath("followerName").asText();
- }else{
- return badRequest("Faltan parámetros [followerName]");
- }
- if(json.has("interestName")){
- interestName = json.findPath("interestName").asText();
- }else{
- return badRequest("Faltan parámetros [interestName]");
- }
- String retorno = MongoBase.addInterest(followerId, followerName,interestName);
- if (retorno != null) {
- return badRequest("Error añadiendo follower");
- }
- return ok();
- }
- @Security.Authenticated(Secured.class)
- public static Result removeInterestFollower() {
- JsonNode json = request().body().asJson();
- String followerId=null;
- String followerName=null;
- String interestName=null;
- if(json.has("followerId")){
- followerId = json.findPath("followerId").asText();
- }else{
- return badRequest("Faltan parámetros [followerId]");
- }
- if(json.has("interestName")){
- interestName = json.findPath("interestName").asText();
- }else{
- return badRequest("Faltan parámetros [interestName]");
- }
- String retorno = MongoBase.removeInterest(followerId, interestName);
- if (retorno != null) {
- return badRequest("Error haciendo unfollow");
- }
- return ok();
- }
- @Security.Authenticated(Secured.class)
- public static Result addDishToFavourites() {
- JsonNode json = request().body().asJson();
- String userId=null;
- String userName=null;
- String venueName=null;
- String dishId=null;
- if(json.has("userId")){
- userId = json.findPath("userId").asText();
- Logger.error(userId);
- }else{
- return badRequest("Faltan parámetros [userId]");
- }
- if(json.has("userName")){
- userName = json.findPath("userName").asText();
- }else{
- return badRequest("Faltan parámetros [userName]");
- }
- if(json.has("venueName")){
- venueName = json.findPath("venueName").asText();
- }else{
- return badRequest("Faltan parámetros [interestName]");
- }
- if(json.has("dishId")){
- dishId = json.findPath("dishId").asText();
- }else{
- return badRequest("Faltan parámetros [dishId]");
- }
- String retorno = MongoBase.addDishToFavourites(userId,userName,dishId,venueName);
- if (retorno != null) {
- Logger.error("Error añadiendo plato a favourites");
- return badRequest("Error añadiendo plato a la Favourites");
- }
- return ok();
- }
- @Security.Authenticated(Secured.class)
- public static Result removeDishFromFavourites() {
- JsonNode json = request().body().asJson();
- String userId=null;
- String dishId=null;
- if(json.has("userId")){
- userId = json.findPath("userId").asText();
- }else{
- return badRequest("Faltan parámetros [userId]");
- }
- if(json.has("dishId")){
- dishId = json.findPath("dishId").asText();
- }else{
- return badRequest("Faltan parámetros [dishId]");
- }
- String retorno = MongoBase.removeDishFromFavourites(userId, dishId);
- if (retorno != null) {
- return badRequest("Error eliminando plato de Favourites");
- }
- return ok();
- }
- @Security.Authenticated(Secured.class)
- public static Result addVenueToFavourites() {
- JsonNode json = request().body().asJson();
- String userId=null;
- String userName=null;
- String venueName=null;
- String venueId=null;
- if(json.has("userId")){
- userId = json.findPath("userId").asText();
- }else{
- return badRequest("Faltan parámetros [userId]");
- }
- if(json.has("userName")){
- userName = json.findPath("userName").asText();
- }else{
- return badRequest("Faltan parámetros [userName]");
- }
- if(json.has("venueName")){
- venueName = json.findPath("venueName").asText();
- }else{
- return badRequest("Faltan parámetros [interestName]");
- }
- if(json.has("venueId")){
- venueId = json.findPath("venueId").asText();
- }else{
- return badRequest("Faltan parámetros [venueId]");
- }
- String retorno = MongoBase.addVenueToFavourites(userId,userName,venueId,venueName);
- if (retorno != null) {
- return badRequest("Error añadiendo venue a la Favourites");
- }
- return ok();
- }
- @Security.Authenticated(Secured.class)
- public static Result removeVenueFromFavourites() {
- JsonNode json = request().body().asJson();
- String userId=null;
- String venueId=null;
- if(json.has("userId")){
- userId = json.findPath("userId").asText();
- }else{
- return badRequest("Faltan parámetros [userId]");
- }
- if(json.has("venueId")){
- venueId = json.findPath("venueId").asText();
- }else{
- return badRequest("Faltan parámetros [venueId]");
- }
- String retorno = MongoBase.removeVenueFromFavourites(userId, venueId);
- if (retorno != null) {
- return badRequest("Error eliminando venue de Favourites");
- }
- return ok();
- }
- @Security.Authenticated(Secured.class)
- public static Result addPublicationToFavourites() {
- JsonNode json = request().body().asJson();
- String userId=null;
- String userName=null;
- String venueName=null;
- String venueId=null;
- String pubId=null;
- if(json.has("userId")){
- userId = json.findPath("userId").asText();
- }else{
- return badRequest("Faltan parámetros [userId]");
- }
- if(json.has("userName")){
- userName = json.findPath("userName").asText();
- }else{
- return badRequest("Faltan parámetros [userName]");
- }
- if(json.has("venueName")){
- venueName = json.findPath("venueName").asText();
- }else{
- return badRequest("Faltan parámetros [venueName]");
- }
- if(json.has("venueId")){
- venueId = json.findPath("venueId").asText();
- }else{
- return badRequest("Faltan parámetros [venueId]");
- }
- if(json.has("pubId")){
- pubId = json.findPath("pubId").asText();
- }else{
- return badRequest("Faltan parámetros [pubId]");
- }
- String retorno = MongoBase.addPublicationToFavourites(userId,userName,pubId,venueId,venueName);
- if (retorno != null) {
- return badRequest("Error añadiendo pub a la Favourites");
- }
- return ok("To muy guapo");
- }
- @Security.Authenticated(Secured.class)
- public static Result removePublicationFromFavourites() {
- JsonNode json = request().body().asJson();
- String userId=null;
- String pubId=null;
- String venueId=null;
- if(json.has("userId")){
- userId = json.findPath("userId").asText();
- }else{
- return badRequest("Faltan parámetros [userId]");
- }
- if(json.has("pubId")){
- pubId = json.findPath("pubId").asText();
- }else{
- return badRequest("Faltan parámetros [pubId]");
- }
- String retorno = MongoBase.removePublicationFromFavourites(userId, pubId);
- if (retorno != null) {
- return badRequest("Error eliminando pub de Favourites");
- }
- return ok();
- }
- public static Result sendPassword() {
- JsonNode json = request().body().asJson();
- String mail = json.findPath("mail").asText();
- if (mail == null) {
- Logger.debug("mail=null");
- return badRequest("No has escrito ningun mail.");
- }
- String password = MongoBase.retrievePassword(mail);
- if (password == null) {
- Logger.debug("password=null");
- return badRequest("La dirección de correo introducida no tiene asociada ninguna contraseña");
- }
- MailerAPI mailSender = play.Play.application().plugin(MailerPlugin.class).email();
- mailSender.setSubject("Recordatorio de tu password");
- mailSender.addRecipient(mail);
- mailSender.addFrom("Registro toptasting <register@toptasting.com>");
- mailSender.send("Tu password es: " + password);
- Logger.info("Password reenviado a " + mail);
- return ok("Password enviado: combrueba tu correo");
- }
- public static Result createUser() {
- User user = new User();
- JsonNode json = request().body().asJson();
- if (json.has("mail")) {
- user.setMail(json.get("mail").asText());
- }
- if (json.has("user")) {
- user.setUser(json.get("user").asText());
- }
- if (json.has("password")) {
- user.setPassword(json.get("password").asText());
- }
- if (json.has("date")) {
- user.setDate(json.get("date").asText());
- }
- if (json.has("location")) {
- user.setLocation(json.get("location").asText());
- }
- if (user.getMail() == null || user.getPassword() == null || user.getUser() == null || user.getDate() == null) {
- Logger.info("Error insertando usuario: error en los parametros");
- return badRequest("Missing parameter/s [mail][user][password][date]");
- }
- if(json.has("gcmId")){
- user.setGcmId(json.get("gcmId").asText());
- }
- if (json.has("birthday")) {
- user.setBirthday(json.get("birthday").asText());
- }
- if (json.has("gender")) {
- user.setGenre(json.get("gender").asText());
- }
- if (json.has("phone")) {
- user.setPhone(json.get("phone").asText());
- }
- if (json.has("photoURL")) {
- user.setPhotoURL(json.get("photoURL").asText());
- }
- if (json.has("fbid")) {
- user.setFbid(json.get("fbid").asText());
- }
- String id=MongoBase.insertUser(user);
- if (id!=null) {
- return ok(id);
- } else {
- Logger.info("Error insertando usuario.");
- return badRequest("Error al insertar el usuario");
- }
- }
- public static Result createFBUser() {
- User user = new User();
- JsonNode json = request().body().asJson();
- Logger.info("Creando usuario FB " + json.toString());
- if (json.has("mail")) {
- user.setMail(json.get("mail").asText());
- }
- if (json.has("user")) {
- user.setUser(json.get("user").asText());
- }
- if (json.has("fbId")) {
- user.setFbid(json.get("fbId").asText());
- }
- if (json.has("date")) {
- user.setDate(json.get("date").asText());
- }
- if (json.has("photoURL")) {
- user.setPhotoURL(json.get("photoURL").asText());
- }
- if (json.has("birthday")) {
- user.setBirthday(json.get("birthday").asText());
- }
- if (json.has("gender")) {
- user.setGenre(json.get("gender").asText());
- }
- user.setPassword("");
- if (user.getMail() == null || user.getFbid() == null || user.getUser() == null || user.getDate() == null) {
- Logger.info("Error insertando usuario facebook: error en los parametros");
- return badRequest("Missing parameter/s [mail][user][fbId][date]");
- }
- if (json.has("birthday")) {
- user.setBirthday(json.get("birthday").asText());
- }
- if (json.has("gender")) {
- user.setGenre(json.get("gender").asText());
- }
- if (json.has("phone")) {
- user.setPhone(json.get("phone").asText());
- }
- if (json.has("photoURL")) {
- user.setPhotoURL(json.get("photoURL").asText());
- }
- String id=MongoBase.insertFBUser(user);
- if (id!=null) {
- return ok(id);
- } else {
- Logger.info("Error insertando usuario.");
- return badRequest("Error al insertar el usuario");
- }
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result createReview() {
- JsonNode json = request().body().asJson();
- String dishId = json.findPath("dishId").asText();
- if (dishId == null || json.findPath("points") == null) {
- return null;
- }
- Review review = new Review(json);
- Logger.info("Review" + json.toString());
- //ESTO ES UNA JODIENDA
- Dish d=MongoBase.findDishById(dishId);//esto es para coger el nombre dle plato, pero igual se puede hacer de otra manera
- review.venueName=d.venueName;
- ////
- if (!MongoBase.insertReview(review, dishId)) {
- return badRequest("Error insertando Review");
- }
- if (!review.photoURL.endsWith("sinImagenDish.png") && d.photoURL.endsWith("sinImagenDish.png")) {
- MongoBase.updateDishPhoto(dishId, review.photoURL);
- }
- return ok("Review insertada correctamente");
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result createDraft() {
- JsonNode json = request().body().asJson();
- Draft draft = new Draft(json);
- Logger.info("Draft" + json.toString());
- if (!MongoBase.insertDraft(draft)) {
- return badRequest("Error insertando Draft");
- }
- //ESTO ES UNA JODIENDA
- if (!draft.photoURL.endsWith("sinImagenDish.png") && MongoBase.findDishById(draft.dishId.toString()).photoURL.endsWith("sinImagenDish.png")) {
- MongoBase.updateDishPhoto(draft.dishId.toString(), draft.photoURL);
- }
- return ok("Review insertada correctamente");
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result completeDraft() {
- JsonNode json = request().body().asJson();
- String dishId = json.findPath("dishId").asText();
- if (dishId == null || json.findPath("points") == null) {
- return null;
- }
- Review review = new Review(json);
- Logger.info("Review" + json.toString());
- if (!MongoBase.completeDraft(review, dishId)) {
- return badRequest("Error completando Draft");
- }
- //ESTO ES UNA JODIENDA
- if (!review.photoURL.endsWith("sinImagenDish.png") && MongoBase.findDishById(dishId).photoURL.endsWith("sinImagenDish.png")) {
- MongoBase.updateDishPhoto(dishId, review.photoURL);
- }
- return ok("Review insertada correctamente");
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result deleteDraft() {
- JsonNode json = request().body().asJson();
- String dishId = json.findPath("dishId").asText();
- String userId = json.findPath("userId").asText();
- if (dishId == null || userId == null) {
- return null;
- }
- if (!MongoBase.deleteDraft(new ObjectId(userId), new ObjectId(dishId))) {
- return badRequest("Error borrando Draft");
- }
- return ok("draft borrado");
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result deleteReview() {
- JsonNode json = request().body().asJson();
- String dishId = json.findPath("dishId").asText();
- String userId = json.findPath("userId").asText();
- if (dishId == null || userId == null) {
- return null;
- }
- if (!MongoBase.deleteReview(userId, dishId)) {
- return badRequest("Error borrando Review");
- }
- return ok("Review borrada");
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result createPublication() {
- Publication pub=new Publication();
- JsonNode json = request().body().asJson();
- if (json.has("venueId")) {
- pub.setVenueId(json.get("venueId").asText());
- }
- else{
- return badRequest("Missing parameter [venueId]");
- }
- if (json.has("title")) {
- pub.setTitle(json.get("title").asText());
- }
- else{
- return badRequest("Missing parameter [title]");
- }
- if (json.has("venueName")) {
- pub.setVenueName(json.get("venueName").asText());
- }
- else{
- return badRequest("Missing parameter [venueName]");
- }
- if (json.has("creationDate")) {
- pub.setCreationDate(json.get("creationDate").asText());
- }
- else{
- return badRequest("Missing parameter [creationDate]");
- }
- if (json.has("photoURL")) {
- pub.setPhotoURL(json.get("photoURL").asText());
- }
- if (json.has("description")) {
- pub.setLongDescription(json.get("longDescription").asText());
- }
- if (json.has("venueLocation")) {
- pub.setVenueLocation(json.get("venueLocation").asText());
- }
- if (json.has("endDate")) {
- pub.setEndDate(json.get("endDate").asText());
- }
- if (json.has("startDate")) {
- pub.setStartDate(json.get("startDate").asText());
- }
- if (json.has("photoURL")) {
- pub.setPhotoURL(json.get("photoURL").asText());
- }
- if (json.has("photoURL")) {
- pub.setPhotoURL(json.get("photoURL").asText());
- }
- if (json.has("interests")) {
- pub.setInterests(json.findValuesAsText("interests"));
- }
- MongoBase.createPublication(pub);
- return ok("Pub enviada con éxito");
- }
- @Security.Authenticated(SecuredWS.class)
- public static Result findFeeds() {
- String retorno = MongoBase.findFeeds();
- if (retorno == null) {
- return badRequest("Error en la busqueda");
- }
- return ok(retorno);
- }
- public static Result login() {
- return ok(
- login.render(form(Login.class))
- );
- }
- public static Result logout() {
- session().clear();
- flash("success", "You've been logged out");
- return redirect(
- routes.Application.login()
- );
- }
- public static Result authenticate() {
- Form<Login> loginForm = form(Login.class).bindFromRequest();
- if (loginForm.hasErrors()) {
- session().clear();
- System.out.println(loginForm.errorsAsJson());
- return badRequest(login.render(loginForm));
- } else {
- session().clear();
- session("mail", loginForm.get().mail);
- session("role", loginForm.get().role);
- if(session().get("role").equalsIgnoreCase("venue")){
- session("venueId",MongoBase.findVenueIdByClientMail(loginForm.get().mail));
- return redirect(
- routes.VenuePanel.blank()
- );
- }else if(session().get("role").equalsIgnoreCase("admin")){
- return redirect(
- routes.AdminPanel.blank()
- );
- }
- else{
- return redirect(
- routes.Application.index()
- );
- }
- }
- }
- public static Result clientcontact() {
- Form<ClientContact> loginForm = form(ClientContact.class).bindFromRequest();
- if (loginForm.hasErrors()) {
- return badRequest(negocios.render(loginForm));
- } else { flash("success", "Formulario enviado, en breve contactaremos contigo. Muchas gracias por tu interés!");
- ClientContact cc=loginForm.get();
- /* final String username = "info@toptasting.com"; // email address by which registered on zoho (another domain based)
- final String password = "TistaElPelirrojete.07";
- Properties props = new Properties();
- props.put("mail.smtp.auth", "true");
- props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
- props.setProperty("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
- props.put("mail.smtp.starttls.enable", "true");
- props.setProperty("mail.smtp.socketFactory.fallback","false");
- props.setProperty("mail.smtp.socketFactory.port","465");
- props.put("mail.smtp.startssl.enable", "true");
- props.put("mail.smtp.host", "smtp.zoho.com");
- props.put("mail.smtp.port", "465");
- Session session = Session.getInstance(props,
- new javax.mail.Authenticator() {
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(username, password);
- }
- });
- try {
- Transport trans = session.getTransport("smtp");
- trans.connect("smtp.zoho.com", 465, "info@toptasting.com", "TistaElPelirrojete.07");
- Message message = new MimeMessage(session);
- message.setFrom(new InternetAddress("info@toptasting.com"));
- message.setRecipients(Message.RecipientType.TO,
- InternetAddress.parse("info@toptasting.com"));
- message.setSubject("Contacto Solicitado");
- message.setText("Solicitud de contacto recibida: ");
- trans.send(message);
- System.out.println("Done");
- } catch (MessagingException e) {
- throw new RuntimeException(e);
- }*/
- MailerAPI mailSender = play.Play.application().plugin(MailerPlugin.class).email();
- mailSender.setSubject("Un negocio solicita contacto");
- mailSender.addRecipient("info@toptasting.com");
- mailSender.addFrom("Formulario de contacto <info@toptasting.com>");
- mailSender.send("Solicitud de contacto recibida.\n "+"\nNombre de Contacto: "+cc.name+"\nEmail de contacto: "+cc.mail+"\nTeléfono de contacto: "+cc.phone+"\nNombre del negocio: "+cc.business);
- return ok(negocios.render(form(ClientContact.class)));
- }
- }
- public static Result logoutWS() {
- session().clear();
- return ok("Logout OK");
- }
- public static Result loginWS() {
- JsonNode json = request().body().asJson();
- String mail = json.findPath("mail").asText();
- String password = json.findPath("password").asText();
- String user = MongoBase.logUser(mail, password);
- if (user == null) {
- session().clear();
- return badRequest("Error en la autenticacion");
- } else {
- session().clear();
- session("mail", mail);
- return ok(user);
- }
- }
- public static F.Promise<Result> loginFB() {
- JsonNode responseJson;
- final JsonNode json = request().body().asJson();
- final String mail = json.findPath("fbUser").findPath("mail").asText();
- String token = json.findPath("userToken").asText();
- String auth = FB_APP_ID + "|" + FB_APP_SECRET;
- Logger.debug(json.toString());
- Logger.debug("en LoginFb");
- WSRequestHolder fbRequest = WS.url("https://graph.facebook.com/debug_token").setQueryParameter("input_token", token).setQueryParameter("access_token", auth);
- F.Promise<Result> resultado = fbRequest.get().map(
- new F.Function<WS.Response, Result>() {
- @Override
- public Result apply(WS.Response response) throws Throwable {
- Logger.info("RESPUESTA= " + response.getBody() + " " + response.getStatusText());
- JsonNode responseJson = response.asJson().get("data");
- if (responseJson.hasNonNull("app_id") && responseJson.get("app_id").asText().equalsIgnoreCase(FB_APP_ID) && responseJson.hasNonNull("is_valid") && responseJson.get("is_valid").asBoolean()) {
- User fbUser=new User();
- fbUser.setFbData(json.findPath("fbUser"));
- Logger.debug("JOSON",json);
- String ttUser = MongoBase.loginFBUser(fbUser, responseJson.get("user_id").asText());
- if (ttUser == null) {
- session().clear();
- return status(202);
- //devolvemos 202 para ue el cliente sepa que el token es correcto pero no hay un usuario registrado
- }
- session().clear();
- session("mail", mail);
- return ok(ttUser);
- //el token era correcto y el usuario estaba registrado
- }
- session().clear();
- return badRequest("Token invalido");
- }
- });
- return resultado;
- }
- public static F.Promise<Result> sendNotification(Notification notification, List<String> suscribers){
- if(suscribers.size()==0){
- Logger.debug("Sin seguidores");
- return Akka.future(
- new Callable<Result>() {
- public Result call() {
- return ok();
- }
- }
- );
- }
- JsonObject parameters=new JsonObject();
- JsonArray direcciones=new JsonArray();
- for(String suscriber:suscribers){
- direcciones.add(new JsonPrimitive(suscriber));
- }
- parameters.add("registration_ids",direcciones);
- parameters.addProperty("userIp","5.56.61.165");
- parameters.add("data", new JsonParser().parse(notification.asJson()));
- Logger.info("Parameters: "+parameters.toString());
- String auth = "AIzaSyD_v66gszhbLwY0iBGCi37Tsb467ruzs0o";
- WS.WSRequestHolder messageRequest = WS.url("https://android.googleapis.com/gcm/send").setHeader("Authorization", "key=" + auth).setContentType("application/json");
- return messageRequest.post(parameters.toString()).map(
- new F.Function<WS.Response, Result>() {
- @Override
- public Result apply(WS.Response response) throws Throwable {
- switch(response.getStatus()){
- case 200: Logger.info("GCM messages correctos");
- flash("success", "Envíado!");
- return redirect(
- routes.AdminPanel.blank()
- );
- case 400:
- Logger.error("Error enviando notificaciones: JSON incorrecto");
- flash("error", "Mal JSON");
- return redirect(
- routes.AdminPanel.blank()
- );
- case 401:
- Logger.error("Error enviando notificaciones: autenticación incorrecta");
- flash("error", "Mala Autenticación!");
- return redirect(
- routes.AdminPanel.blank()
- );
- default:
- Logger.error("Error enviando notificaciones: error en el servicio de Google");
- flash("error", "ROMPISTE GOOGLE!!!! BOOOM!");
- return redirect(
- routes.AdminPanel.blank()
- );
- }
- }
- }
- );
- }
- public static Result geoReferenciar() {
- JsonNode json = request().body().asJson();
- String direction = json.findPath("direction").asText();
- if (direction == null) {
- return badRequest("Missing parameter/s [direction]");
- }
- //return ok(Utils.Geocoding.getGeocode(direction));
- String direccionFormateada = direction.replaceAll(" ", "+");
- Logger.info("http://maps.googleapis.com/maps/api/geocode/json?address=" + direccionFormateada + "&sensor=false");
- String url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + direccionFormateada + "&sensor=false";
- JsonNode responseJson;
- try {
- byte[] b = url.getBytes("UTF-8");
- WSRequestHolder googleRequest = WS.url(new String(b, "UTF-8"));
- responseJson = googleRequest.get().get().asJson();
- } catch (Exception ex) {
- Logger.error(ex.getMessage());
- return badRequest("QUE CAGADA!");
- }
- return ok(responseJson.toString());
- }
- public static class Login {
- public String mail;
- public String password;
- public String role = "user";
- public String validate() {
- System.out.println(mail);
- if (MongoBase.loginAdmin(mail, password)) {
- role = "admin";
- return null;
- }
- else if(MongoBase.loginVenue(mail,password)){
- role="venue";
- return null;
- }
- /* if (MongoBase.loginUser(mail, password) != null) {
- role = "user";
- return null;
- }
- return "Invalid user or password";
- }
- */
- return "Invalid user";
- }
- }
- public static class ClientContact{
- public String name;
- public String mail;
- public String phone;
- public String business;
- public String validate() {
- if(name==null||name.length()<1){
- return "Tienes que introducir un nombre de contacto.";
- }
- if(checkMail(mail)||(phone!=null&&phone.length()>8)){
- return null;
- }
- if(!checkMail(mail)){
- return "El email tiene un formato incorrecto.";
- }
- if(phone==null||phone.length()<9){
- return "El teléfono no parece correcto.";
- }
- return null;
- }
- }
- /**
- * Comprueba que una dirección de correo electrónico está correctamente formado.
- * @param mail
- * @return
- */
- public static boolean checkMail(String mail) {
- Pattern rfc2822 = Pattern.compile(
- "^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$"
- );
- return rfc2822.matcher(mail).matches();
- }
- }