Search in sources :

Example 1 with SupporterDeviceSubscription

use of net.osmand.server.api.repo.DeviceSubscriptionsRepository.SupporterDeviceSubscription in project OsmAnd-tools by osmandapp.

the class SubscriptionController method purchased.

// Android sends
// parameters.put("userid", userId);
// parameters.put("sku", info.getSku());
// parameters.put("orderId", info.getOrderId());
// parameters.put("purchaseToken", info.getPurchaseToken());
// parameters.put("email", email);
// parameters.put("token", token);
// parameters.put("version", Version.getFullVersion(ctx));
// parameters.put("lang", ctx.getLanguage() + "");
// parameters.put("nd", ctx.getAppInitializer().getFirstInstalledDays() + "");
// parameters.put("ns", ctx.getAppInitializer().getNumberOfStarts() + "");
// parameters.put("aid", ctx.getUserAndroidId());
// iOS sends
// [params setObject:@"ios" forKey:@"os"];
// [params setObject:userId forKey:@"userid"];
// [params setObject:token forKey:@"token"];
// [params setObject:sku forKey:@"sku"];
// [params setObject:transactionId forKey:@"purchaseToken"];
// [params setObject:receiptStr forKey:@"payload"];
// [params setObject:email forKey:@"email"];
@PostMapping(path = { "/purchased", "/purchased.php" })
public ResponseEntity<String> purchased(HttpServletRequest request) {
    SupporterDeviceSubscription subscr = new SupporterDeviceSubscription();
    // it was mixed in early ios versions, so orderid was passed as purchaseToken and payload as purchaseToken;
    // "ios".equals(request.getParameter("purchaseToken")) ||
    boolean ios = Algorithms.isEmpty(request.getParameter("orderId"));
    subscr.purchaseToken = ios ? request.getParameter("payload") : request.getParameter("purchaseToken");
    subscr.orderId = ios ? request.getParameter("purchaseToken") : request.getParameter("orderId");
    subscr.sku = request.getParameter("sku");
    subscr.timestamp = new Date();
    if (isEmpty(subscr.orderId)) {
        return error("Please validate the purchase (orderid is empty).");
    }
    if (isEmpty(subscr.purchaseToken)) {
        return error("Please validate the purchase (purchase token is empty).");
    }
    String userId = request.getParameter("userid");
    if (!isEmpty(userId)) {
        connectUserWithOrderId(userId, subscr.orderId, request);
    }
    Optional<SupporterDeviceSubscription> subscrOpt = subscriptionsRepository.findById(new SupporterDeviceSubscriptionPrimaryKey(subscr.sku, subscr.orderId));
    if (subscrOpt.isPresent() && !Algorithms.isEmpty(subscr.purchaseToken)) {
        SupporterDeviceSubscription dbSubscription = subscrOpt.get();
        if (!Algorithms.isEmpty(dbSubscription.purchaseToken) && !Algorithms.objectEquals(subscr.purchaseToken, dbSubscription.purchaseToken)) {
            if (dbSubscription.valid != null && dbSubscription.valid.booleanValue()) {
                dbSubscription.prevvalidpurchasetoken = dbSubscription.purchaseToken;
            }
            dbSubscription.valid = null;
            dbSubscription.kind = null;
            dbSubscription.purchaseToken = subscr.purchaseToken;
            subscriptionsRepository.save(dbSubscription);
        }
        return ResponseEntity.ok("{ \"res\" : \"OK\" }");
    }
    subscriptionsRepository.save(subscr);
    return ResponseEntity.ok("{ \"res\" : \"OK\" }");
}
Also used : SupporterDeviceSubscription(net.osmand.server.api.repo.DeviceSubscriptionsRepository.SupporterDeviceSubscription) SupporterDeviceSubscriptionPrimaryKey(net.osmand.server.api.repo.DeviceSubscriptionsRepository.SupporterDeviceSubscriptionPrimaryKey) Date(java.util.Date) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 2 with SupporterDeviceSubscription

use of net.osmand.server.api.repo.DeviceSubscriptionsRepository.SupporterDeviceSubscription in project OsmAnd-tools by osmandapp.

the class SubscriptionController method validateReceiptIos.

@PostMapping(path = { "/ios-receipt-validate" })
public ResponseEntity<String> validateReceiptIos(HttpServletRequest request) throws Exception {
    String receipt = request.getParameter("receipt");
    JsonObject receiptObj = validationService.loadReceiptJsonObject(receipt, false);
    if (receiptObj != null) {
        Map<String, Object> result = new HashMap<>();
        List<InAppReceipt> inAppReceipts = validationService.loadInAppReceipts(receiptObj);
        if (inAppReceipts != null) {
            if (inAppReceipts.size() == 0) {
                result.put("eligible_for_introductory_price", "true");
                result.put("eligible_for_subscription_offer", "false");
                result.put("result", false);
                result.put("status", NO_SUBSCRIPTIONS_FOUND_STATUS);
                return ResponseEntity.ok(jsonMapper.writeValueAsString(result));
            } else {
                result.put("eligible_for_introductory_price", isEligibleForIntroductoryPrice(inAppReceipts) ? "true" : "false");
                // update existing subscription purchaseToken
                for (InAppReceipt r : inAppReceipts) {
                    if (r.isSubscription()) {
                        Optional<SupporterDeviceSubscription> subscription = subscriptionsRepository.findById(new SupporterDeviceSubscriptionPrimaryKey(r.getProductId(), r.getOrderId()));
                        if (subscription.isPresent()) {
                            SupporterDeviceSubscription s = subscription.get();
                            if (!Algorithms.objectEquals(s.purchaseToken, receipt)) {
                                s.purchaseToken = receipt;
                                subscriptionsRepository.saveAndFlush(s);
                            }
                        }
                    }
                }
                List<Map<String, String>> activeSubscriptions = new ArrayList<>();
                Map<String, Object> validationResult = validationService.validateReceipt(receiptObj, activeSubscriptions);
                result.putAll(validationResult);
                result.put("eligible_for_subscription_offer", isEligibleForSubscriptionOffer(inAppReceipts, activeSubscriptions) ? "true" : "false");
                return ResponseEntity.ok(jsonMapper.writeValueAsString(result));
            }
        }
    }
    return error("Cannot load receipt.");
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JsonObject(com.google.gson.JsonObject) SupporterDeviceSubscriptionPrimaryKey(net.osmand.server.api.repo.DeviceSubscriptionsRepository.SupporterDeviceSubscriptionPrimaryKey) SupporterDeviceSubscription(net.osmand.server.api.repo.DeviceSubscriptionsRepository.SupporterDeviceSubscription) JsonObject(com.google.gson.JsonObject) InAppReceipt(net.osmand.live.subscriptions.ReceiptValidationHelper.InAppReceipt) Map(java.util.Map) HashMap(java.util.HashMap) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Example 3 with SupporterDeviceSubscription

use of net.osmand.server.api.repo.DeviceSubscriptionsRepository.SupporterDeviceSubscription in project OsmAnd-tools by osmandapp.

the class UserdataController method checkOrderIdPremium.

private String checkOrderIdPremium(String orderid) {
    if (Algorithms.isEmpty(orderid)) {
        return "no subscription provided";
    }
    String errorMsg = "no subscription present";
    List<SupporterDeviceSubscription> lst = subscriptionsRepo.findByOrderId(orderid);
    for (SupporterDeviceSubscription s : lst) {
        // s.sku could be checked for premium
        if (s.expiretime == null || s.expiretime.getTime() < System.currentTimeMillis() || s.checktime == null) {
            if (s.sku.startsWith(OSMAND_PRO_ANDROID_SUBSCRIPTION)) {
                s = revalidateGoogleSubscription(s);
            } else if (s.sku.contains(OSMAND_PRO_HUAWEI_SUBSCRIPTION_1) || s.sku.contains(OSMAND_PRO_HUAWEI_SUBSCRIPTION_2)) {
                s = revalidateHuaweiSubscription(s);
            } else if (s.sku.contains(OSMAND_PRO_AMAZON_SUBSCRIPTION)) {
                s = revalidateAmazonSubscription(s);
            }
        }
        if (s.valid == null || !s.valid.booleanValue()) {
            errorMsg = "no valid subscription present";
        } else if (!s.sku.startsWith(OSMAND_PRO_ANDROID_SUBSCRIPTION) && !s.sku.startsWith(OSMAND_PROMO_SUBSCRIPTION) && !s.sku.contains(OSMAND_PRO_HUAWEI_SUBSCRIPTION_1) && !s.sku.contains(OSMAND_PRO_HUAWEI_SUBSCRIPTION_2) && !s.sku.contains(OSMAND_PRO_AMAZON_SUBSCRIPTION)) {
            errorMsg = "subscription is not eligible for OsmAnd Cloud";
        } else {
            if (s.expiretime != null && s.expiretime.getTime() > System.currentTimeMillis()) {
                return null;
            } else {
                errorMsg = "subscription is expired or not validated yet";
            }
        }
    }
    return errorMsg;
}
Also used : SupporterDeviceSubscription(net.osmand.server.api.repo.DeviceSubscriptionsRepository.SupporterDeviceSubscription)

Example 4 with SupporterDeviceSubscription

use of net.osmand.server.api.repo.DeviceSubscriptionsRepository.SupporterDeviceSubscription in project OsmAnd-tools by osmandapp.

the class ApiController method getSubscriptions.

@GetMapping(path = { "/subscriptions/get" })
@ResponseBody
public String getSubscriptions(@RequestParam(required = false) String userId, @RequestParam(required = false) String userToken, @RequestParam(required = false) String orderId, @RequestHeader HttpHeaders headers, HttpServletRequest request) throws IOException, ParseException {
    MessageParams params = new MessageParams();
    params.hostAddress = request.getRemoteAddr();
    if (headers.getFirst("X-Forwarded-For") != null) {
        params.hostAddress = headers.getFirst("X-Forwarded-For");
    }
    if (!Algorithms.isEmpty(userId) && !Algorithms.isEmpty(userToken) && Algorithms.isEmpty(orderId)) {
        Optional<Supporter> sup = supportersRepository.findByUserId(Long.parseLong(userId));
        if (sup.isPresent()) {
            Supporter s = sup.get();
            if (userToken.equals(s.token)) {
                orderId = sup.get().orderId;
            }
        }
    }
    if (!Algorithms.isEmpty(orderId)) {
        List<SupporterDeviceSubscription> subscriptions = subscriptionsRepository.findByOrderId(orderId);
        List<Object> res = new ArrayList<>();
        for (SupporterDeviceSubscription sub : subscriptions) {
            Map<String, String> subMap = new HashMap<>();
            subMap.put("sku", sub.sku);
            if (sub.valid != null) {
                subMap.put("valid", sub.valid.toString());
            }
            String state = "undefined";
            if (sub.starttime != null) {
                subMap.put("start_time", String.valueOf(sub.starttime.getTime()));
            }
            if (sub.expiretime != null) {
                long expireTimeMs = sub.expiretime.getTime();
                int paymentState = sub.paymentstate == null ? 1 : sub.paymentstate.intValue();
                boolean autoRenewing = sub.autorenewing == null ? false : sub.autorenewing.booleanValue();
                if (expireTimeMs > System.currentTimeMillis()) {
                    if (paymentState == 1 && autoRenewing) {
                        state = "active";
                    } else if (paymentState == 1 && !autoRenewing) {
                        state = "cancelled";
                    } else if (paymentState == 0 && autoRenewing) {
                        state = "in_grace_period";
                    }
                } else {
                    if (paymentState == 0 && autoRenewing) {
                        state = "on_hold";
                    } else if (paymentState == 1 && autoRenewing) {
                        state = "paused";
                    } else if (paymentState == 1 && !autoRenewing) {
                        state = "expired";
                    }
                }
                subMap.put("expire_time", String.valueOf(expireTimeMs));
            }
            subMap.put("state", state);
            res.add(subMap);
        }
        return jsonMapper.writeValueAsString(res);
    }
    return "{}";
}
Also used : HashMap(java.util.HashMap) MessageParams(net.osmand.server.api.services.MotdService.MessageParams) ArrayList(java.util.ArrayList) SupporterDeviceSubscription(net.osmand.server.api.repo.DeviceSubscriptionsRepository.SupporterDeviceSubscription) Supporter(net.osmand.server.api.repo.SupportersRepository.Supporter) GetMapping(org.springframework.web.bind.annotation.GetMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 5 with SupporterDeviceSubscription

use of net.osmand.server.api.repo.DeviceSubscriptionsRepository.SupporterDeviceSubscription in project OsmAnd-tools by osmandapp.

the class AdminController method registerPromo.

@PostMapping(path = { "/register-promo" })
public String registerPromo(Model model, @RequestParam(required = true) String comment, final RedirectAttributes redirectAttrs) throws JsonProcessingException {
    SupporterDeviceSubscription deviceSub = new SupporterDeviceSubscription();
    deviceSub.sku = "promo_website";
    deviceSub.orderId = UUID.randomUUID().toString();
    deviceSub.kind = "promo";
    Calendar c = Calendar.getInstance();
    c.setTimeInMillis(System.currentTimeMillis());
    deviceSub.timestamp = c.getTime();
    deviceSub.starttime = c.getTime();
    deviceSub.valid = true;
    deviceSub.purchaseToken = comment;
    c.add(Calendar.YEAR, 1);
    deviceSub.expiretime = c.getTime();
    subscriptionsRepository.save(deviceSub);
    if (emailSender.isEmail(comment)) {
        String email = comment;
        PremiumUser existingUser = usersRepository.findByEmail(email);
        if (existingUser == null) {
            PremiumUser pu = new PremiumUsersRepository.PremiumUser();
            pu.email = email;
            pu.regTime = new Date();
            pu.orderid = deviceSub.orderId;
            usersRepository.saveAndFlush(pu);
            deviceSub.purchaseToken += " (email sent & registered)";
            emailSender.sendOsmAndCloudPromoEmail(comment, deviceSub.orderId);
        } else {
            deviceSub.purchaseToken += " (ERROR: email is already registered)";
        }
    }
    redirectAttrs.addFlashAttribute("subscriptions", Collections.singleton(deviceSub));
    return "redirect:info#audience";
}
Also used : SupporterDeviceSubscription(net.osmand.server.api.repo.DeviceSubscriptionsRepository.SupporterDeviceSubscription) Calendar(java.util.Calendar) PremiumUser(net.osmand.server.api.repo.PremiumUsersRepository.PremiumUser) Date(java.util.Date) PostMapping(org.springframework.web.bind.annotation.PostMapping)

Aggregations

SupporterDeviceSubscription (net.osmand.server.api.repo.DeviceSubscriptionsRepository.SupporterDeviceSubscription)6 PostMapping (org.springframework.web.bind.annotation.PostMapping)4 ArrayList (java.util.ArrayList)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 SupporterDeviceSubscriptionPrimaryKey (net.osmand.server.api.repo.DeviceSubscriptionsRepository.SupporterDeviceSubscriptionPrimaryKey)2 PremiumUser (net.osmand.server.api.repo.PremiumUsersRepository.PremiumUser)2 JsonObject (com.google.gson.JsonObject)1 Calendar (java.util.Calendar)1 Map (java.util.Map)1 InAppReceipt (net.osmand.live.subscriptions.ReceiptValidationHelper.InAppReceipt)1 Supporter (net.osmand.server.api.repo.SupportersRepository.Supporter)1 MessageParams (net.osmand.server.api.services.MotdService.MessageParams)1 UserFilesResults (net.osmand.server.controllers.pub.UserdataController.UserFilesResults)1 GetMapping (org.springframework.web.bind.annotation.GetMapping)1 ResponseBody (org.springframework.web.bind.annotation.ResponseBody)1