示例#1
0
        private void DoCropsEditorConnections(Node editor, TreeItem entry)
        {
            activeCrop = crops[entry];
            if (activeCrop.Bonus == null)
            {
                activeCrop.Bonus = new CropData.Bonus_();
            }

            DoEditorConnections(editor, activeCrop);

            var intEdit = editor.GetNode <SpinBox>("Texture/SubImageEditor/Values/SubRectWidth/SpinBox");

            intEdit.Value    = 128;
            intEdit.Editable = false;
            intEdit          = editor.GetNode <SpinBox>("Texture/SubImageEditor/Values/SubRectHeight/SpinBox");
            intEdit.Value    = 32;
            intEdit.Editable = false;

            intEdit          = editor.GetNode <SpinBox>("SeedTexture/SubImageEditor/Values/SubRectWidth/SpinBox");
            intEdit.Value    = 16;
            intEdit.Editable = false;
            intEdit          = editor.GetNode <SpinBox>("SeedTexture/SubImageEditor/Values/SubRectHeight/SpinBox");
            intEdit.Value    = 16;
            intEdit.Editable = false;

            intEdit          = editor.GetNode <SpinBox>("GiantTexture/SubImageEditor/Values/SubRectWidth/SpinBox");
            intEdit.Value    = 48;
            intEdit.Editable = false;
            intEdit          = editor.GetNode <SpinBox>("GiantTexture/SubImageEditor/Values/SubRectHeight/SpinBox");
            intEdit.Value    = 63;
            intEdit.Editable = false;
        }
示例#2
0
 public void ReadCropData(string path)
 {
     cropData = JsonUtility.FromJson <CropData>(PlayerPrefs.GetString(path));
     print("I have read my data sir: " + PlayerPrefs.GetString(path));
     parent = GetComponentInParent <TileSystem>();
     CheckGrowth();
 }
示例#3
0
 public void RemoveCrop(CropData crop)
 {
     if (!crop)
     {
         return;
     }
     dieCrops.Add(crop);
 }
示例#4
0
 public void Init(CropData data, Field parent, Vector3 position)
 {
     Clear();
     data.entity          = this;
     Data                 = data;
     Data.OnStageChanged += OnStageChange;
     Parent               = parent;
     transform.SetParent(parent.transform);
     transform.position = position;
 }
示例#5
0
        /// <summary>
        /// Crops the in-memory Image according to the arguments provided.
        /// </summary>
        /// <param name="image">The in-memory image to be cropped.</param>
        /// <param name="x">X coordinate of the top left corner of the rectangle to be retained.</param>
        /// <param name="y">Y coordinate of the top left corner of the rectangle to be retained.</param>
        /// <param name="width">Width (in pixels) of the rectangle to be retained.</param>
        /// <param name="height">Height (in pixels) of the rectangle to be retained.</param>
        private static void CropImage(Image image, CropData cropData)
        {
            // Adjust crop values for scaled down preview image
            double scaleFactor = image.Width / cropData.prevW;

            image.Mutate(ctx => ctx.Crop(
                             new Rectangle(
                                 (int)(cropData.x * scaleFactor),
                                 (int)(cropData.y * scaleFactor),
                                 (int)(cropData.width * scaleFactor),
                                 (int)(cropData.height * scaleFactor)
                                 )));
        }
示例#6
0
        public async Task <IActionResult> Crop(int id, CropData args)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest("Invalid arguments provided to crop image."));
                }

                BaseMedia media = await _Db.Media.FindAsync(id);

                if (media == null)
                {
                    return(NotFound("The requested media file does not exist."));
                }

                ImageMedia oldImage = media as ImageMedia;
                if (oldImage == null)
                {
                    return(BadRequest("Unable to crop non-image media file."));
                }

                // Generate new GUID
                string filename = Guid.NewGuid().ToString() + Path.GetExtension(oldImage.Filename);

                // Save the file again, passing in crop data
                ImageUtils.SaveImage(await System.IO.File.ReadAllBytesAsync(oldImage.FilePath), Path.Combine("Storage", "Media", "Images", filename), args);

                ImageMedia newImage = new ImageMedia
                {
                    Title = oldImage.Title,
                    Alt   = oldImage.Alt,
                    Name  = oldImage.Name + "_cropped",
                    // other values provided by cropping code
                };

                await _Db.AddAsync(newImage);

                await _Db.SaveChangesAsync();

                _Logger.LogDebug("Media file {0} cropped - new file ID is {1}", id, newImage.Id);

                return(Ok(newImage.Id)); // Todo: may want to pass back something else here
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error cropping media file {0}: {1}", id, ex.Message);
                _Logger.LogError(ex.StackTrace);
                return(BadRequest("Something went wrong, please try again later."));
            }
        }
    private void SelectTile()
    {
        selectedTilePosition = tileMapReadController.GetGridPosition(Input.mousePosition, true);
        TileBase tileBase = tileMapReadController.GetTileBase(selectedTilePosition);

        try
        {
            TileData tileData = tileMapReadController.GetTileData(tileBase);
            if (!(tileData is null))
            {
                if (!fields.ContainsKey((Vector2Int)selectedTilePosition))
                {
                    fields.Add((Vector2Int)selectedTilePosition, tileData);
                }
                else
                {
                    fields[(Vector2Int)selectedTilePosition] = tileData;
                }
            }
        }
        catch
        {
            return;
        }

        selectedCropPosition = cropsReadController.GetGridPosition(Input.mousePosition, true);
        TileBase cropBase = cropsReadController.GetTileBase(selectedTilePosition);

        try
        {
            CropData cropData = cropsReadController.GetCropData(cropBase);
            if (!(cropData is null))
            {
                if (!crops.ContainsKey((Vector2Int)selectedTilePosition))
                {
                    crops.Add((Vector2Int)selectedTilePosition, cropData);
                }
                else
                {
                    crops[(Vector2Int)selectedTilePosition] = cropData;
                }
            }
        }
        catch
        {
            return;
        }
    }
示例#8
0
        private static unsafe SerializableDocument GetSerializable(DataObject data, out CropData cropData)
        {
            MemoryStream         pixiStream = data.GetData("PIXI") as MemoryStream;
            SerializableDocument document   = PixiParser.Deserialize(pixiStream);

            if (data.GetDataPresent(typeof(CropData)))
            {
                cropData = CropData.FromStream(data.GetData(typeof(CropData)) as MemoryStream);
            }
            else
            {
                cropData = new CropData(document.Width, document.Height, 0, 0);
            }

            return(document);
        }
示例#9
0
    public CropData PlantCrop(CropInformation crop)
    {
        if (!crop)
        {
            return(null);
        }

        if (spaceOccup < crop.Size)
        {
            return(null);
        }

        CropData cropData = new CropData(crop, this);

        Crops.Add(cropData);
        return(cropData);
    }
示例#10
0
    public void PlantCrop(CropInformation crop, Vector3 position)
    {
        if (!crop)
        {
            return;
        }

        if (FData.spaceOccup < crop.Size)
        {
            MessageManager.Instance.New("空间不足");
            return;
        }

        CropData cropData = FData.PlantCrop(crop);

        if (cropData)
        {
            Crop entity = ObjectPool.Get(crop.Prefab, transform);
            entity.Init(cropData, this, position);
            NotifyCenter.PostNotify(FieldManager.FieldCropPlanted, this, cropData);
        }
    }
示例#11
0
 private void Clear()
 {
     if (Data && Data.Info)
     {
         GameManager.Crops.TryGetValue(Data.Info, out var crops);
         if (crops != null)
         {
             crops.Remove(this);
             if (crops.Count < 1)
             {
                 GameManager.Crops.Remove(Data.Info);
             }
         }
         Data = null;
     }
     if (Parent)
     {
         Parent.Crops.Remove(this);
         Parent = null;
     }
     resourceInfo = null;
     UI           = null;
 }
示例#12
0
        /// <summary>
        /// Saves an Image to the specified path and creates scaled down copies where appropriate.
        ///
        /// Use within a try-catch.
        /// </summary>
        /// <returns>Dictionary to be peristed in the database, under [ImageMedia.Filenames].</returns>
        public static Dictionary <string, dynamic> SaveImage(Image image, string path, CropData cropData = null)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException("Path must not be null or empty.");
            }

            // If crop instructions are provided, crop the image before saving.
            if (cropData != null)
            {
                CropImage(image, cropData);
            }

            // Save the original image
            image.Save(path);

            // Save any required smaller versions of the image, return results to calling method.
            return(SaveScaledCopies(image, Path.GetFileName(path)));
        }
示例#13
0
        public static Dictionary <string, dynamic> SaveImage(string base64Image, string path, CropData cropData = null)
        {
            Image image = Image.Load(base64Image.DecodeBase64Bytes());

            return(SaveImage(image, path, cropData));
        }
示例#14
0
        public static Dictionary <string, dynamic> SaveImage(byte[] imageBytes, string path, CropData cropData = null)
        {
            Image image = Image.Load(imageBytes);

            return(SaveImage(image, path, cropData));
        }
示例#15
0
        private void FillPlotInfo(Plot p)
        {
            plotInfoLstbx.Items.Clear();
            plotInfoLstbx.Items.Add("Plot Summary");
            plotInfoLstbx.Items.Add(p.PlotId + ":  SoilType: " + p.getSoilType());
            if (p.getNumberOfCrops() != 0)
            {
                plotInfoLstbx.Items.Add("Total Crops Set in Plot" + p.getNumberOfCrops().ToString());
                plotInfoLstbx.Items.Add("Crops Harvested: " + p.getNumberOfHarvestedCrops().ToString());
            }
            else
            {
                plotInfoLstbx.Items.Add("No Crops Set in Plot");
            }

            plotInfoLstbx.Items.Add("------------------");
            if (p.getNumberOfCrops() != 0)
            {
                if (p.plotWeeks[rcaea.simulation.CurrentWeek].isEmpty)
                {
                    string[] Crops = p.getAllCropNamesInPlotWithStartEndDates();
                    foreach (string s in Crops)
                    {
                        plotInfoLstbx.Items.Add(s);
                    }
                }
                else
                {
                    CropData currentPlot = p.GetCurrentCropData();
                    if (currentPlot != null)
                    {
                        if (currentPlot.getIsAlive())
                        {
                            plotInfoLstbx.Items.Add("Currently Selected Crop");
                            plotInfoLstbx.Items.Add("Set at " + rcaea.simulation.DateToString(currentPlot.GetBeginDate()));
                            plotInfoLstbx.Items.Add("Matured at: " + rcaea.simulation.DateToString(currentPlot.GetEndDate()));
                            plotInfoLstbx.Items.Add("Current Status: ");
                            plotInfoLstbx.Items.Add(currentPlot.getHealth());
                            if (fertilizerCbx.SelectedIndex != 0)
                            {
                                plotInfoLstbx.Items.Add("Current Water Costs: ");
                                plotInfoLstbx.Items.Add(currentPlot.GetWaterCost());
                            }
                            if (wateringCbx.SelectedIndex != 0)
                            {
                                plotInfoLstbx.Items.Add("Current Fertilizer Costs: ");
                                plotInfoLstbx.Items.Add(Convert.ToInt32(currentPlot.GetFertilizerCost()));
                            }
                            if (currentPlot.GetYield() != 0)
                            {
                                plotInfoLstbx.Items.Add("Total Costs: ");
                                plotInfoLstbx.Items.Add(currentPlot.GetTotalCost());
                                plotInfoLstbx.Items.Add("Total Profit: ");
                                plotInfoLstbx.Items.Add(currentPlot.getProfits());
                                plotInfoLstbx.Items.Add("Yield: ");
                                plotInfoLstbx.Items.Add(currentPlot.GetYield());
                                plotInfoLstbx.Items.Add("Possible Yield: ");
                                plotInfoLstbx.Items.Add(currentPlot.getIdealYield());
                            }
                        }
                        else
                        {
                            plotInfoLstbx.Items.Add("Currently Selected Crop");
                            plotInfoLstbx.Items.Add("Set at " + rcaea.simulation.DateToString(currentPlot.GetBeginDate()));
                            plotInfoLstbx.Items.Add("Current Status: ");
                            plotInfoLstbx.Items.Add(currentPlot.getHealth());
                        }
                    }
                }
            }
        }
示例#16
0
 public void CompleteCrop(CropData cropData)
 {
     _host.CompleteCrop(cropData);
 }
示例#17
0
        private void loadData(IContentPack contentPack)
        {
            Log.info($"\t{contentPack.Manifest.Name} {contentPack.Manifest.Version} by {contentPack.Manifest.Author} - {contentPack.Manifest.Description}");

            // load objects
            DirectoryInfo objectsDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "Objects"));

            if (objectsDir.Exists)
            {
                foreach (DirectoryInfo dir in objectsDir.EnumerateDirectories())
                {
                    string relativePath = $"Objects/{dir.Name}";

                    // load data
                    ObjectData obj = contentPack.ReadJsonFile <ObjectData>($"{relativePath}/object.json");
                    if (obj == null)
                    {
                        continue;
                    }

                    // save object
                    obj.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/object.png");
                    if (obj.IsColored)
                    {
                        obj.textureColor = contentPack.LoadAsset <Texture2D>($"{relativePath}/color.png");
                    }
                    this.objects.Add(obj);

                    // save ring
                    if (obj.Category == ObjectData.Category_.Ring)
                    {
                        this.myRings.Add(obj);
                    }

                    // Duplicate check
                    if (dupObjects.ContainsKey(obj.Name))
                    {
                        Log.error($"Duplicate object: {obj.Name} just added by {contentPack.Manifest.Name}, already added by {dupObjects[obj.Name].Manifest.Name}!");
                    }
                    else
                    {
                        dupObjects[obj.Name] = contentPack;
                    }
                }
            }

            // load crops
            DirectoryInfo cropsDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "Crops"));

            if (cropsDir.Exists)
            {
                foreach (DirectoryInfo dir in cropsDir.EnumerateDirectories())
                {
                    string relativePath = $"Crops/{dir.Name}";

                    // load data
                    CropData crop = contentPack.ReadJsonFile <CropData>($"{relativePath}/crop.json");
                    if (crop == null)
                    {
                        continue;
                    }

                    // save crop
                    crop.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/crop.png");
                    crops.Add(crop);

                    // save seeds
                    crop.seed = new ObjectData
                    {
                        texture                 = contentPack.LoadAsset <Texture2D>($"{relativePath}/seeds.png"),
                        Name                    = crop.SeedName,
                        Description             = crop.SeedDescription,
                        Category                = ObjectData.Category_.Seeds,
                        Price                   = crop.SeedPurchasePrice,
                        CanPurchase             = true,
                        PurchaseFrom            = crop.SeedPurchaseFrom,
                        PurchasePrice           = crop.SeedPurchasePrice,
                        PurchaseRequirements    = crop.SeedPurchaseRequirements ?? new List <string>(),
                        NameLocalization        = crop.SeedNameLocalization,
                        DescriptionLocalization = crop.SeedDescriptionLocalization
                    };

                    // TODO: Clean up this chunk
                    // I copy/pasted it from the unofficial update decompiled
                    string   str   = "";
                    string[] array = new[] { "spring", "summer", "fall", "winter" }
                    .Except(crop.Seasons)
                    .ToArray();
                    foreach (var season in array)
                    {
                        str += $"/z {season}";
                    }
                    string strtrimstart = str.TrimStart(new char[] { '/' });
                    if (crop.SeedPurchaseRequirements != null && crop.SeedPurchaseRequirements.Count > 0)
                    {
                        for (int index = 0; index < crop.SeedPurchaseRequirements.Count; index++)
                        {
                            if (SeasonLimiter.IsMatch(crop.SeedPurchaseRequirements[index]))
                            {
                                crop.SeedPurchaseRequirements[index] = strtrimstart;
                                Log.warn($"        Faulty season requirements for {crop.SeedName}!\n        Fixed season requirements: {crop.SeedPurchaseRequirements[index]}");
                            }
                        }
                        if (!crop.SeedPurchaseRequirements.Contains(str.TrimStart('/')))
                        {
                            Log.trace($"        Adding season requirements for {crop.SeedName}:\n        New season requirements: {strtrimstart}");
                            crop.seed.PurchaseRequirements.Add(strtrimstart);
                        }
                    }
                    else
                    {
                        Log.trace($"        Adding season requirements for {crop.SeedName}:\n        New season requirements: {strtrimstart}");
                        crop.seed.PurchaseRequirements.Add(strtrimstart);
                    }

                    objects.Add(crop.seed);

                    // Duplicate check
                    if (dupCrops.ContainsKey(crop.Name))
                    {
                        Log.error($"Duplicate crop: {crop.Name} just added by {contentPack.Manifest.Name}, already added by {dupCrops[crop.Name].Manifest.Name}!");
                    }
                    else
                    {
                        dupCrops[crop.Name] = contentPack;
                    }
                }
            }

            // load fruit trees
            DirectoryInfo fruitTreesDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "FruitTrees"));

            if (fruitTreesDir.Exists)
            {
                foreach (DirectoryInfo dir in fruitTreesDir.EnumerateDirectories())
                {
                    string relativePath = $"FruitTrees/{dir.Name}";

                    // load data
                    FruitTreeData tree = contentPack.ReadJsonFile <FruitTreeData>($"{relativePath}/tree.json");
                    if (tree == null)
                    {
                        continue;
                    }

                    // save fruit tree
                    tree.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/tree.png");
                    fruitTrees.Add(tree);

                    // save seed
                    tree.sapling = new ObjectData
                    {
                        texture                 = contentPack.LoadAsset <Texture2D>($"{relativePath}/sapling.png"),
                        Name                    = tree.SaplingName,
                        Description             = tree.SaplingDescription,
                        Category                = ObjectData.Category_.Seeds,
                        Price                   = tree.SaplingPurchasePrice,
                        CanPurchase             = true,
                        PurchaseRequirements    = tree.SaplingPurchaseRequirements,
                        PurchaseFrom            = tree.SaplingPurchaseFrom,
                        PurchasePrice           = tree.SaplingPurchasePrice,
                        NameLocalization        = tree.SaplingNameLocalization,
                        DescriptionLocalization = tree.SaplingDescriptionLocalization
                    };
                    objects.Add(tree.sapling);

                    // Duplicate check
                    if (dupFruitTrees.ContainsKey(tree.Name))
                    {
                        Log.error($"Duplicate fruit tree: {tree.Name} just added by {contentPack.Manifest.Name}, already added by {dupFruitTrees[tree.Name].Manifest.Name}!");
                    }
                    else
                    {
                        dupFruitTrees[tree.Name] = contentPack;
                    }
                }
            }

            // load big craftables
            DirectoryInfo bigCraftablesDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "BigCraftables"));

            if (bigCraftablesDir.Exists)
            {
                foreach (DirectoryInfo dir in bigCraftablesDir.EnumerateDirectories())
                {
                    string relativePath = $"BigCraftables/{dir.Name}";

                    // load data
                    BigCraftableData craftable = contentPack.ReadJsonFile <BigCraftableData>($"{relativePath}/big-craftable.json");
                    if (craftable == null)
                    {
                        continue;
                    }

                    // save craftable
                    craftable.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/big-craftable.png");
                    bigCraftables.Add(craftable);

                    // Duplicate check
                    if (dupBigCraftables.ContainsKey(craftable.Name))
                    {
                        Log.error($"Duplicate big craftable: {craftable.Name} just added by {contentPack.Manifest.Name}, already added by {dupBigCraftables[craftable.Name].Manifest.Name}!");
                    }
                    else
                    {
                        dupBigCraftables[craftable.Name] = contentPack;
                    }
                }
            }

            // load hats
            DirectoryInfo hatsDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "Hats"));

            if (hatsDir.Exists)
            {
                foreach (DirectoryInfo dir in hatsDir.EnumerateDirectories())
                {
                    string relativePath = $"Hats/{dir.Name}";

                    // load data
                    HatData hat = contentPack.ReadJsonFile <HatData>($"{relativePath}/hat.json");
                    if (hat == null)
                    {
                        continue;
                    }

                    // save object
                    hat.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/hat.png");
                    hats.Add(hat);

                    // Duplicate check
                    if (dupHats.ContainsKey(hat.Name))
                    {
                        Log.error($"Duplicate hat: {hat.Name} just added by {contentPack.Manifest.Name}, already added by {dupHats[hat.Name].Manifest.Name}!");
                    }
                    else
                    {
                        dupBigCraftables[hat.Name] = contentPack;
                    }
                }
            }

            // Load weapons
            // load objects
            DirectoryInfo weaponsDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "Weapons"));

            if (weaponsDir.Exists)
            {
                foreach (DirectoryInfo dir in weaponsDir.EnumerateDirectories())
                {
                    string relativePath = $"Weapons/{dir.Name}";

                    // load data
                    WeaponData weapon = contentPack.ReadJsonFile <WeaponData>($"{relativePath}/weapon.json");
                    if (weapon == null)
                    {
                        continue;
                    }

                    // save object
                    weapon.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/weapon.png");
                    weapons.Add(weapon);

                    // Duplicate check
                    if (dupWeapons.ContainsKey(weapon.Name))
                    {
                        Log.error($"Duplicate weapon: {weapon.Name} just added by {contentPack.Manifest.Name}, already added by {dupWeapons[weapon.Name].Manifest.Name}!");
                    }
                    else
                    {
                        dupBigCraftables[weapon.Name] = contentPack;
                    }
                }
            }
        }
示例#18
0
        public async Task <IActionResult> Index(IFormCollection request)
        {
            try
            {
                // Create required directories if not existing
                EnsureInit();

                // Deserialize cropping data if applicable
                CropData cropData = null;
                if (request.Str("cropData") != null)
                {
                    cropData = JsonConvert.DeserializeObject <CropData>(request.Str("cropData"));
                }


                // Original filename
                string uploadedName = request.Str("filename");

                // Generate a backend filename for the uploaded file - same extension as uploaded file.
                string filename = Guid.NewGuid().ToString() + Path.GetExtension(uploadedName);

                string fileType = request.Str("fileType");

                // Determine what type of file has been uploaded and act accordingly (may want to refactor these)

                // FOR IMAGES
                if (MediaType.MimesForCategory(MediaCategory.Image).Contains(fileType))
                {
                    string filepath = Path.Combine("Storage", "Media", "Images", filename);

                    // Save image and all associated versions of it.
                    var filedata = ImageUtils.SaveImage(request.Str("file")
                                                        .Split(',')[1], filepath, cropData);

                    // Create database record to track images
                    ImageMedia dbImageMedia = new ImageMedia {
                        Name      = Path.GetFileNameWithoutExtension(uploadedName),
                        MediaType = MediaType.FromString(fileType),
                        FilePath  = filepath,
                        Size      = filedata["size"],
                        Title     = request.Str("title"),
                        Alt       = request.Str("alt"),
                        Width     = filedata["width"],
                        Height    = filedata["height"],
                        Versions  = filedata["versions"]
                    };

                    await _Db.AddAsync(dbImageMedia);
                }

                // FOR AUDIO
                else if (MediaType.MimesForCategory(MediaCategory.Audio).Contains(fileType))
                {
                    string filepath = Path.Combine("Storage", "Media", "Audio", filename);

                    // Save the audio file
                    byte[] bytes = request.Str("file").Split(',')[1].DecodeBase64Bytes();
                    await System.IO.File.WriteAllBytesAsync(filepath, bytes);

                    // Read the audio file to determine its duration - it will either be mp3(mpeg) or wav

                    // Configure ffprobe path using appsettings values
                    FFProbe probe = new FFProbe();
                    probe.ToolPath = _Config["ffprobePath"];

                    // If running linux, look for ffprobe instaed of ffprobe.exe
                    if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
                    {
                        probe.FFProbeExeName = "ffprobe";
                    }

                    // Get audio file metadata
                    MediaInfo mediaInfo = probe.GetMediaInfo(Path.Combine(_HostingEnv.ContentRootPath, filepath));

                    // Create the media database record
                    AudioMedia audioMedia = new AudioMedia
                    {
                        Name      = Path.GetFileNameWithoutExtension(uploadedName),
                        MediaType = MediaType.FromString(fileType),
                        FilePath  = filepath,
                        Size      = new FileInfo(filepath).Length,
                        Duration  = Math.Round(mediaInfo.Duration.TotalSeconds)
                    };

                    await _Db.AddAsync(audioMedia);
                }

                // FOR GENERAL
                else if (MediaType.MimesForCategory(MediaCategory.General).Contains(fileType))
                {
                    string filepath = Path.Combine("Storage", "Media", "Documents", filename);

                    // Save the file
                    byte[] bytes = request.Str("file").Split(',')[1].DecodeBase64Bytes();
                    System.IO.File.WriteAllBytes(filepath, bytes);

                    // Create the media database record
                    GeneralMedia generalMedia = new GeneralMedia
                    {
                        Name      = Path.GetFileNameWithoutExtension(uploadedName),
                        MediaType = MediaType.FromString(fileType),
                        FilePath  = filepath,
                        Size      = new FileInfo(filepath).Length,
                    };

                    await _Db.AddAsync(generalMedia);
                }

                else
                {
                    return(new UnsupportedMediaTypeResult());
                }

                await _Db.SaveChangesAsync();

                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error uploading file: {0}", ex.Message);
                _Logger.LogError(ex.StackTrace);
                return(BadRequest(new ResponseHelper("Something went wrong, please contact the devloper if the problem persists", ex.Message)));
            }
        }
示例#19
0
        private void loadData(IContentPack contentPack)
        {
            Log.info($"\t{contentPack.Manifest.Name} {contentPack.Manifest.Version} by {contentPack.Manifest.Author} - {contentPack.Manifest.Description}");

            // load objects
            DirectoryInfo objectsDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "Objects"));

            if (objectsDir.Exists)
            {
                foreach (DirectoryInfo dir in objectsDir.EnumerateDirectories())
                {
                    string relativePath = $"Objects/{dir.Name}";

                    // load data
                    ObjectData obj = contentPack.ReadJsonFile <ObjectData>($"{relativePath}/object.json");
                    if (obj == null)
                    {
                        continue;
                    }

                    // save object
                    obj.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/object.png");
                    if (obj.IsColored)
                    {
                        obj.textureColor = contentPack.LoadAsset <Texture2D>($"{relativePath}/color.png");
                    }
                    this.objects.Add(obj);

                    // save ring
                    if (obj.Category == ObjectData.Category_.Ring)
                    {
                        this.myRings.Add(obj);
                    }
                }
            }

            // load crops
            DirectoryInfo cropsDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "Crops"));

            if (cropsDir.Exists)
            {
                foreach (DirectoryInfo dir in cropsDir.EnumerateDirectories())
                {
                    string relativePath = $"Crops/{dir.Name}";

                    // load data
                    CropData crop = contentPack.ReadJsonFile <CropData>($"{relativePath}/crop.json");
                    if (crop == null)
                    {
                        continue;
                    }

                    // save crop
                    crop.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/crop.png");
                    crops.Add(crop);

                    // save seeds
                    crop.seed = new ObjectData
                    {
                        texture              = contentPack.LoadAsset <Texture2D>($"{relativePath}/seeds.png"),
                        Name                 = crop.SeedName,
                        Description          = crop.SeedDescription,
                        Category             = ObjectData.Category_.Seeds,
                        Price                = crop.SeedPurchasePrice,
                        CanPurchase          = true,
                        PurchaseFrom         = crop.SeedPurchaseFrom,
                        PurchasePrice        = crop.SeedPurchasePrice,
                        PurchaseRequirements = crop.SeedPurchaseRequirements ?? new List <string>()
                    };

                    // TODO: Clean up this chunk
                    // I copy/pasted it from the unofficial update decompiled
                    string   str   = "";
                    string[] array = new string[]
                    {
                        "spring",
                        "summer",
                        "fall",
                        "winter"
                    }.Except(crop.Seasons).ToArray <string>();
                    for (int i = 0; i < array.Length; i++)
                    {
                        string season = array[i];
                        str += string.Format("/z {0}", season);
                    }
                    string strtrimstart = str.TrimStart(new char[] { '/' });
                    if (crop.SeedPurchaseRequirements != null && crop.SeedPurchaseRequirements.Count > 0)
                    {
                        for (int index = 0; index < crop.SeedPurchaseRequirements.Count; index++)
                        {
                            if (SeasonLimiter.IsMatch(crop.SeedPurchaseRequirements[index]))
                            {
                                crop.SeedPurchaseRequirements[index] = strtrimstart;
                                Log.warn(string.Format("        Faulty season requirements for {0}!\n", crop.SeedName) + string.Format("        Fixed season requirements: {0}", crop.SeedPurchaseRequirements[index]));
                            }
                        }
                        if (!crop.SeedPurchaseRequirements.Contains(str.TrimStart(new char[] { '/' })))
                        {
                            Log.trace(string.Format("        Adding season requirements for {0}:\n", crop.SeedName) + string.Format("        New season requirements: {0}", strtrimstart));
                            crop.seed.PurchaseRequirements.Add(strtrimstart);
                        }
                    }
                    else
                    {
                        Log.trace(string.Format("        Adding season requirements for {0}:\n", crop.SeedName) + string.Format("        New season requirements: {0}", strtrimstart));
                        crop.seed.PurchaseRequirements.Add(strtrimstart);
                    }

                    objects.Add(crop.seed);
                }
            }

            // load fruit trees
            DirectoryInfo fruitTreesDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "FruitTrees"));

            if (fruitTreesDir.Exists)
            {
                foreach (DirectoryInfo dir in fruitTreesDir.EnumerateDirectories())
                {
                    string relativePath = $"FruitTrees/{dir.Name}";

                    // load data
                    FruitTreeData tree = contentPack.ReadJsonFile <FruitTreeData>($"{relativePath}/tree.json");
                    if (tree == null)
                    {
                        continue;
                    }

                    // save fruit tree
                    tree.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/tree.png");
                    fruitTrees.Add(tree);

                    // save seed
                    tree.sapling = new ObjectData
                    {
                        texture              = contentPack.LoadAsset <Texture2D>($"{relativePath}/sapling.png"),
                        Name                 = tree.SaplingName,
                        Description          = tree.SaplingDescription,
                        Category             = ObjectData.Category_.Seeds,
                        Price                = tree.SaplingPurchasePrice,
                        CanPurchase          = true,
                        PurchaseRequirements = tree.SaplingPurchaseRequirements,
                        PurchaseFrom         = tree.SaplingPurchaseFrom,
                        PurchasePrice        = tree.SaplingPurchasePrice
                    };
                    objects.Add(tree.sapling);
                }
            }

            // load big craftables
            DirectoryInfo bigCraftablesDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "BigCraftables"));

            if (bigCraftablesDir.Exists)
            {
                foreach (DirectoryInfo dir in bigCraftablesDir.EnumerateDirectories())
                {
                    string relativePath = $"BigCraftables/{dir.Name}";

                    // load data
                    BigCraftableData craftable = contentPack.ReadJsonFile <BigCraftableData>($"{relativePath}/big-craftable.json");
                    if (craftable == null)
                    {
                        continue;
                    }

                    // save craftable
                    craftable.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/big-craftable.png");
                    bigCraftables.Add(craftable);
                }
            }

            // load objects
            DirectoryInfo hatsDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "Hats"));

            if (hatsDir.Exists)
            {
                foreach (DirectoryInfo dir in hatsDir.EnumerateDirectories())
                {
                    string relativePath = $"Hats/{dir.Name}";

                    // load data
                    HatData hat = contentPack.ReadJsonFile <HatData>($"{relativePath}/hat.json");
                    if (hat == null)
                    {
                        continue;
                    }

                    // save object
                    hat.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/hat.png");
                    hats.Add(hat);
                }
            }
        }
示例#20
0
        private void loadData(IContentPack contentPack)
        {
            Log.info($"\t{contentPack.Manifest.Name} {contentPack.Manifest.Version} by {contentPack.Manifest.Author} - {contentPack.Manifest.Description}");

            // load objects
            DirectoryInfo objectsDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "Objects"));

            if (objectsDir.Exists)
            {
                foreach (DirectoryInfo dir in objectsDir.EnumerateDirectories())
                {
                    string relativePath = $"Objects/{dir.Name}";

                    // load data
                    ObjectData obj = contentPack.ReadJsonFile <ObjectData>($"{relativePath}/object.json");
                    if (obj == null)
                    {
                        continue;
                    }

                    // save object
                    obj.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/object.png");
                    if (obj.IsColored)
                    {
                        obj.textureColor = contentPack.LoadAsset <Texture2D>($"{relativePath}/color.png");
                    }
                    this.objects.Add(obj);

                    // save ring
                    if (obj.Category == ObjectData.Category_.Ring)
                    {
                        this.myRings.Add(obj);
                    }
                }
            }

            // load crops
            DirectoryInfo cropsDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "Crops"));

            if (cropsDir.Exists)
            {
                foreach (DirectoryInfo dir in cropsDir.EnumerateDirectories())
                {
                    string relativePath = $"Crops/{dir.Name}";

                    // load data
                    CropData crop = contentPack.ReadJsonFile <CropData>($"{relativePath}/crop.json");
                    if (crop == null)
                    {
                        continue;
                    }

                    // save crop
                    crop.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/crop.png");
                    crops.Add(crop);

                    // save seeds
                    crop.seed = new ObjectData
                    {
                        texture              = contentPack.LoadAsset <Texture2D>($"{relativePath}/seeds.png"),
                        Name                 = crop.SeedName,
                        Description          = crop.SeedDescription,
                        Category             = ObjectData.Category_.Seeds,
                        Price                = crop.SeedPurchasePrice,
                        CanPurchase          = true,
                        PurchaseFrom         = crop.SeedPurchaseFrom,
                        PurchasePrice        = crop.SeedPurchasePrice,
                        PurchaseRequirements = crop.SeedPurchaseRequirements ?? new List <string>()
                    };
                    string[] excludeSeasons = new[] { "spring", "summer", "fall", "winter" }.Except(crop.Seasons).ToArray();
                    crop.seed.PurchaseRequirements.Add($"z {string.Join(" ", excludeSeasons)}");
                    objects.Add(crop.seed);
                }
            }

            // load fruit trees
            DirectoryInfo fruitTreesDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "FruitTrees"));

            if (fruitTreesDir.Exists)
            {
                foreach (DirectoryInfo dir in fruitTreesDir.EnumerateDirectories())
                {
                    string relativePath = $"FruitTrees/{dir.Name}";

                    // load data
                    FruitTreeData tree = contentPack.ReadJsonFile <FruitTreeData>($"{relativePath}/tree.json");
                    if (tree == null)
                    {
                        continue;
                    }

                    // save fruit tree
                    tree.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/tree.png");
                    fruitTrees.Add(tree);

                    // save seed
                    tree.sapling = new ObjectData
                    {
                        texture              = contentPack.LoadAsset <Texture2D>($"{relativePath}/sapling.png"),
                        Name                 = tree.SaplingName,
                        Description          = tree.SaplingDescription,
                        Category             = ObjectData.Category_.Seeds,
                        Price                = tree.SaplingPurchasePrice,
                        CanPurchase          = true,
                        PurchaseRequirements = tree.SaplingPurchaseRequirements,
                        PurchaseFrom         = tree.SaplingPurchaseFrom,
                        PurchasePrice        = tree.SaplingPurchasePrice
                    };
                    objects.Add(tree.sapling);
                }
            }

            // load big craftables
            DirectoryInfo bigCraftablesDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "BigCraftables"));

            if (bigCraftablesDir.Exists)
            {
                foreach (DirectoryInfo dir in bigCraftablesDir.EnumerateDirectories())
                {
                    string relativePath = $"BigCraftables/{dir.Name}";

                    // load data
                    BigCraftableData craftable = contentPack.ReadJsonFile <BigCraftableData>($"{relativePath}/big-craftable.json");
                    if (craftable == null)
                    {
                        continue;
                    }

                    // save craftable
                    craftable.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/big-craftable.png");
                    bigCraftables.Add(craftable);
                }
            }

            // load objects
            DirectoryInfo hatsDir = new DirectoryInfo(Path.Combine(contentPack.DirectoryPath, "Hats"));

            if (hatsDir.Exists)
            {
                foreach (DirectoryInfo dir in hatsDir.EnumerateDirectories())
                {
                    string relativePath = $"Hats/{dir.Name}";

                    // load data
                    HatData hat = contentPack.ReadJsonFile <HatData>($"{relativePath}/hat.json");
                    if (hat == null)
                    {
                        continue;
                    }

                    // save object
                    hat.texture = contentPack.LoadAsset <Texture2D>($"{relativePath}/hat.png");
                    hats.Add(hat);
                }
            }
        }