Beispiel #1
0
        public bool UpdateConnection(ConnectionModel model, bool isForExport)
        {
            var connection = _connectionRepository.GetById(model.Id);

            if (connection == null)
            {
                return(false);
            }

            connection.IsActive     = model.IsActive;
            connection.PublicKey    = model.PublicKey;
            connection.SecretKey    = model.SecretKey;
            connection.UpdatedOnUtc = DateTime.UtcNow;
            connection.Url          = model.Url;

            if (isForExport)
            {
                connection.LimitedToManufacturerIds = string.Join(",", model.LimitedToManufacturerIds ?? new int[0]);
                connection.LimitedToStoreIds        = string.Join(",", model.LimitedToStoreIds ?? new int[0]);
            }

            _connectionRepository.Update(connection);
            ConnectionCache.Remove();

            return(true);
        }
Beispiel #2
0
        public ShopConnectorConnectionRecord InsertConnection(ConnectionModel model)
        {
            var utcNow = DateTime.UtcNow;
            ShopConnectorConnectionRecord connection = null;

            if (model.IsForExport)
            {
                var    hmac = new HmacAuthentication();
                string publicKey, secretKey;

                for (var i = 0; i < 9999; ++i)
                {
                    if (hmac.CreateKeys(out publicKey, out secretKey) && !_connectionRepository.TableUntracked.Any(x => x.PublicKey == publicKey))
                    {
                        connection = new ShopConnectorConnectionRecord
                        {
                            IsActive    = true,
                            IsForExport = model.IsForExport,
                            Url         = model.Url,
                            PublicKey   = publicKey,
                            SecretKey   = secretKey,
                            LimitedToManufacturerIds = string.Join(",", model.LimitedToManufacturerIds ?? new int[0]),
                            LimitedToStoreIds        = string.Join(",", model.LimitedToStoreIds ?? new int[0]),
                            CreatedOnUtc             = utcNow,
                            UpdatedOnUtc             = utcNow
                        };
                        break;
                    }
                }
            }
            else
            {
                connection = new ShopConnectorConnectionRecord
                {
                    IsActive    = true,
                    IsForExport = model.IsForExport,
                    Url         = model.Url,
                    PublicKey   = model.PublicKey,
                    SecretKey   = model.SecretKey,
                    LimitedToManufacturerIds = string.Join(",", model.LimitedToManufacturerIds ?? new int[0]),
                    LimitedToStoreIds        = string.Join(",", model.LimitedToStoreIds ?? new int[0]),
                    CreatedOnUtc             = utcNow,
                    UpdatedOnUtc             = utcNow
                };
            }

            if (connection != null)
            {
                _connectionRepository.Insert(connection);
                ConnectionCache.Remove();
            }

            return(connection);
        }
        //public bool SendNotification(int id, bool hasNewData)
        //{
        //	var context = new ShopConnectorRequestContext()
        //	{
        //		ActionMethod = "Notification",
        //		HttpMethod = "POST",
        //		RequestContent = "{0}={1}".FormatInvariant(ShopConnectorCore.Xml.HasNewData, hasNewData.ToString())
        //	};

        //	bool success = SendRequest(context, id);
        //	return success;
        //}

        //public void ProcessNotification()
        //{
        //	var request = HttpContext.Current.Request;
        //	string publicKey = request.Headers[ShopConnectorCore.Header.PublicKey];
        //	var controllingData = ShopConnectorCaching.ControllingData();

        //	var connection = controllingData.Connections.FirstOrDefault(x => x.PublicKey == publicKey && !x.IsForExport);
        //	if (connection != null)
        //	{
        //		controllingData.ConnectionsUpdated = true;
        //		connection.HasNewData = request.Form[ShopConnectorCore.Xml.HasNewData].ToBool();
        //	}
        //}

        public DataExportResult Export(ShopConnectorExportContext context, CancellationToken token, string providerSystemName)
        {
            var provider = _exportProfileService.Value.LoadProvider(providerSystemName);
            var profile  = _exportProfileService.Value.GetSystemExportProfile(providerSystemName);

            if (profile == null)
            {
                profile = _exportProfileService.Value.InsertExportProfile(provider, true);
            }

            if (context.Connection == null)
            {
                var controllingData = ConnectionCache.ControllingData();
                var connection      = controllingData.Connections.FirstOrDefault(x => x.PublicKey == context.PublicKey && x.IsForExport);
                context.Connection = _connectionRepository.GetById(connection.Id);
            }

            var limitedToStoreIds = context.Connection.LimitedToStoreIds.ToIntArray();
            var domain            = _shopConnectorSettings.EnableSkuMapping
                ? context.Connection.Url.ToDomain()
                : string.Empty;

            var request = new DataExportRequest(profile, provider);

            request.CustomData.Add(ShopConnectorCore.Header.PublicKey, context.PublicKey);
            request.CustomData.Add("CategoryIds", context.CategoryIds);
            request.CustomData.Add("StoreIds", limitedToStoreIds);
            request.CustomData.Add("Domain", domain);
            request.HasPermission = true;

            if (providerSystemName == ShopConnectorProductXmlExportProvider.SystemName)
            {
                var fetchFrom = context.Model.FetchFrom.ToDateTimeIso8601();
                var limitedToManufacturerIds = context.Connection.LimitedToManufacturerIds.ToIntArray();

                request.ProductQuery = GetProductQuery(
                    limitedToManufacturerIds,
                    limitedToStoreIds,
                    context.Model.FilterManufacturerIds,
                    context.Model.FilterCategoryId.ToInt(),
                    fetchFrom);
            }

            var result = _dataExporter.Value.Export(request, token);

            return(result);
        }
Beispiel #4
0
        public void DeleteConnection(int id)
        {
            var connection = _connectionRepository.GetById(id);

            if (connection != null)
            {
                // hooks not working here, so do it manually
                // TODO: remove during uninstall too.
                //var mappings = _storeMappingService.GetStoreMappings(connection);

                //mappings.Each(x => _storeMappingService.DeleteStoreMapping(x));

                _connectionRepository.Delete(connection);

                ConnectionCache.Remove();
            }
        }
        public void Import(ProductImportModel model)
        {
            var controllingData = ConnectionCache.ControllingData();

            if (!controllingData.IsImportEnabled)
            {
                _services.Notifier.Error(T("Plugins.SmartStore.ShopConnector.ImportNotActive"));
                return;
            }

            if (_asyncState.Exists <ShopConnectorProcessingInfo>(ShopConnectorPlugin.SystemName))
            {
                _asyncState.Remove <ShopConnectorProcessingInfo>(ShopConnectorPlugin.SystemName);
            }

            var utcNow = DateTime.UtcNow;
            var state  = new ShopConnectorImportState
            {
                ImportCategories         = model.ImportCategories,
                ImportAll                = model.ImportAll,
                ImportFile               = model.ImportFile,
                UpdateExistingProducts   = model.UpdateExistingProducts,
                UpdateExistingCategories = model.UpdateExistingCategories,
                DeleteImportFile         = model.DeleteImportFile,
                TaxCategoryId            = model.TaxCategoryId,
                LimitedToStores          = model.LimitedToStores,
                EventPublishEntityCount  = 100,
                Publish               = model.Publish,
                DisableBuyButton      = model.DisableBuyButton,
                DisableWishlistButton = model.DisableWishlistButton
            };

            try
            {
                state.IgnoreEntityNames = _shopConnectorSettings.IgnoreEntityNames
                                          .SplitSafe(",")
                                          .Select(x => x.TrimSafe())
                                          .ToList();

                if (model.SelectedStoreIds != null && model.SelectedStoreIds.Any())
                {
                    state.SelectedStoreIds = model.SelectedStoreIds.ToList();
                }

                if (!model.ImportAll && !string.IsNullOrWhiteSpace(model.SelectedProductIds))
                {
                    state.SelectedProductIds = model.SelectedProductIds.SplitSafe(",").Select(x => x.ToInt()).ToDictionarySafe(x => x, x => 0);
                }

                var task = AsyncRunner.Run((c, ct, x) =>
                {
                    var obj = x as ShopConnectorImportState;
                    c.Resolve <IShopConnectorImportService>().StartProductImport(obj);
                }, state);

                _services.Notifier.Information(new LocalizedString(T("Plugins.SmartStore.ShopConnector.ImportInProgress")));

                task.Wait(500);
            }
            catch (Exception ex)
            {
                _services.Notifier.Error(ex.ToAllMessages());
                Logger.Error(ex);
            }
        }
        public bool SendRequest(ShopConnectorRequestContext context, int id)
        {
            try
            {
                string val;
                var    controllingData = ConnectionCache.ControllingData();
                var    connection      = controllingData.Connections.FirstOrDefault(x => x.Id == id);
                context.Version    = controllingData.Version;
                context.Connection = connection;

                Debug.Assert(!connection.IsForExport || (connection.IsForExport && context.ActionMethod.IsCaseInsensitiveEqual("Notification")),
                             "Import connection must be used to consume data.", "");

                if (!connection.IsActive)
                {
                    context.ResponseModel = new OperationResultModel(T("Plugins.SmartStore.ShopConnector.ConnectionNotActive"));
                    return(false);
                }

                if (!controllingData.IsImportEnabled)
                {
                    context.ResponseModel = new OperationResultModel(T("Plugins.SmartStore.ShopConnector.ImportNotActive"));
                    return(false);
                }

                context.PublicKey      = connection.PublicKey;
                context.SecretKey      = connection.SecretKey;
                context.HttpAcceptType = "application/atom+xml,application/atomsvc+xml,application/xml";

                if (context.Url.IsEmpty())
                {
                    context.Url = connection.Url.GetEndpointUrl(context.ActionMethod);
                }
                if (context.HttpMethod.IsEmpty())
                {
                    context.HttpMethod = "GET";
                }

                if (context.ActionMethod == "About")
                {
                    var fs = new ShopConnectorFileSystem("About");
                    context.ResponsePath = fs.GetFullFilePath(string.Concat("about-", Guid.NewGuid().ToString(), ".xml"));
                }
                else if (context.ActionMethod == "ProductData")
                {
                    context.ResponsePath = new ShopConnectorFileSystem("Product").GetFilePath(context.RequestContent["DataFileName"]);
                }

                var consumer = new ShopConnectorConsumer();
                var request  = consumer.StartRequest(context);
                consumer.ProcessResponse(context, request);

                context.Success = context.ResponseModel == null;
                if (context.Success)
                {
                    controllingData.ConnectionsUpdated = true;

                    if (context.Headers.TryGetValue("Sm-ShopConnector-RequestCount", out val) && long.TryParse(val, out var requestCount))
                    {
                        connection.RequestCount = requestCount;
                    }
                    if (context.Headers.TryGetValue("Sm-ShopConnector-LastRequest", out val))
                    {
                        connection.LastRequestUtc = val.ToDateTimeIso8601();
                    }
                    if (context.Headers.TryGetValue("Sm-ShopConnector-LastProductCall", out val))
                    {
                        connection.LastProductCallUtc = val.ToDateTimeIso8601();
                    }
                }

                ShopConnectorFileSystem.CleanupDirectories();
            }
            catch (Exception ex)
            {
                context.Success       = false;
                context.ResponseModel = new OperationResultModel(ex);
            }

            return(context.Success);
        }