Ejemplo n.º 1
0
        public void Load(string file)
        {
            this.File = file;

            ImageProcessed = false;
            try {
                Nodes.Clear();

                var contentTemplate = GetContentTemplate(file);

                //parse the json into a model format
                Response = FigmaApiHelper.GetFigmaResponseFromFileContent(contentTemplate);

                //proceses all the views recursively
                foreach (var item in Response.document.children)
                {
                    ProcessNodeRecursively(item, null);
                }
            } catch (System.Net.WebException ex) {
                if (!AppContext.Current.IsApiConfigured)
                {
                    Console.Error.WriteLine($"Cannot connect to Figma server: TOKEN not configured.");
                }
                else
                {
                    Console.Error.WriteLine($"Cannot connect to Figma server: wrong TOKEN?");
                }

                Console.WriteLine(ex);
            } catch (Exception ex) {
                Console.WriteLine($"Error reading remote resources. Ensure you added NewtonSoft nuget or cannot parse the to json?");
                Console.WriteLine(ex);
            }
        }
Ejemplo n.º 2
0
        public void LocalFileTest()
        {
            var file = Path.Combine(currentPath, fileExample);
            var data = File.ReadAllText(file);
            var doc  = FigmaApiHelper.GetFigmaResponseFromFileContent(data);

            Assert.IsNotNull(file);
        }
Ejemplo n.º 3
0
        private async void FigmaUrlTextField_Changed(object sender, EventArgs e)
        {
            ShowLoading(true);

            SelectedFileVersion = null;

            //loads current versions
            versionPopUp.RemoveAllItems();

            RefreshStates();

            if (FigmaApiHelper.TryParseFileUrl(FileId, out string fileId))
            {
                figmaUrlTextField.StringValue = fileId;
            }

            versions = await Task.Run(() => {
                try {
                    var query             = new FigmaFileVersionQuery(fileId);
                    var figmaFileVersions = FigmaSharp.AppContext.Api.GetFileVersions(query).versions;
                    var result            = figmaFileVersions
                                            .GroupByCreatedAt()
                                            .ToArray();
                    return(result);
                } catch (Exception ex) {
                    Console.WriteLine(ex);
                    return(null);
                }
            });

            ShowLoading(false);

            versionMenu.Clear();

            if (versions != null)
            {
                foreach (var item in versions)
                {
                    versionMenu.AddItem(item);
                }

                versionMenu.Generate(versionPopUp.Menu);

                versionPopUp.SelectItem(versionMenu.CurrentMenu);
                SelectedFileVersion = versionMenu.CurrentVersion;
            }

            RefreshStates();
        }
Ejemplo n.º 4
0
 public FigmaResponse GetFigmaResponseFromContent(string template) =>
 FigmaApiHelper.GetFigmaResponseFromContent(template);
Ejemplo n.º 5
0
 public string GetManifestResource(Assembly assembly, string file) =>
 FigmaApiHelper.GetManifestResource(assembly, file);
Ejemplo n.º 6
0
 public string GetFigmaFileContent(string file, string token) =>
 FigmaApiHelper.GetFigmaFileContent(file, token);
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            const string noimages   = "--noimages";
            const string outputFile = "downloaded.figma";

            Console.WriteLine();
            Console.ForegroundColor = ConsoleColor.DarkCyan;
            Console.WriteLine("Figma Remote File Importer");
            Console.WriteLine("--------------------------");
            Console.WriteLine();

            Console.ForegroundColor = default(ConsoleColor);

            #region Parameters

            if (args.Length == 0)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Error. No parameters defined");
                Console.ForegroundColor = default(ConsoleColor);

                Console.WriteLine("");
                Console.WriteLine($"dotnet FigmaFileExporter.dll [document_id] [figma_token] {{output_directory}} {{{noimages}}}");
                Console.WriteLine("");
                return;
            }

            string token = null;
            if (args.Length > 1)
            {
                token = args[1];
            }

            if (string.IsNullOrEmpty(token))
            {
                Console.WriteLine("Error. Figma Token is not defined.");
                return;
            }

            Console.WriteLine($"Token: {token}");

            string outputDirectory = null;
            if (args.Length > 2 && Directory.Exists(outputDirectory))
            {
                outputDirectory = args[2];
            }

            if (outputDirectory == null)
            {
                Console.WriteLine("Output directory is not defined. Using current directory like default.");
                outputDirectory = Directory.GetCurrentDirectory();
            }

            Console.WriteLine($"Default Directory: {outputDirectory}");

            var processImages = !args.Any(s => s.ToLower() == noimages);

            #endregion

            FigmaSharp.AppContext.Current.SetAccessToken(token);

            var fileId = args[0];

            var outputFilePath = Path.Combine(outputDirectory, outputFile);
            if (File.Exists(outputFilePath))
            {
                File.Delete(outputFilePath);
            }

            Console.WriteLine();
            Console.WriteLine("[Import] Starting from remote document '{0}' ({1} images) in local file: {2}", fileId, processImages ? "with" : "without", outputFilePath);


            var content = FigmaApiHelper.GetFigmaFileContent(fileId);
            File.WriteAllText(outputFilePath, content);

            Console.WriteLine("[Import] Success.");

            if (processImages)
            {
                var figmaResponse = FigmaApiHelper.GetFigmaResponseFromContent(content);

                var mainNode         = figmaResponse.document.children.FirstOrDefault();
                var figmaModelImages = mainNode.OfTypeImage().ToArray();

                Console.WriteLine("[Import] Downloading {0} image/s...", figmaModelImages.Length);

                var figmaImageIds = figmaModelImages.Select(s => s.id).ToArray();
                if (figmaImageIds.Length > 0)
                {
                    var figmaImageResponse = FigmaApiHelper.GetFigmaImages(fileId, figmaImageIds);
                    FileHelper.SaveFiles(outputDirectory, ".png", figmaImageResponse.images);
                }
                Console.WriteLine("[Import] Success.");
            }
        }
Ejemplo n.º 8
0
        void ProcessRemoteImages(List <ProcessedNode> imageFigmaNodes, ImageQueryFormat imageFormat)
        {
            try
            {
                var totalImages = imageFigmaNodes.Count();
                //TODO: figma url has a limited character in urls we fixed the limit to 10 ids's for each call
                var numberLoop = (totalImages / CallNumber) + 1;

                //var imageCache = new Dictionary<string, List<string>>();
                List <Tuple <string, List <string> > > imageCacheResponse = new List <Tuple <string, List <string> > >();
                Console.WriteLine("Detected a total of {0} possible {1} images.  ", totalImages, imageFormat);

                var images = new List <string>();
                for (int i = 0; i < numberLoop; i++)
                {
                    var vectors = imageFigmaNodes.Skip(i * CallNumber).Take(CallNumber);
                    Console.WriteLine("[{0}/{1}] Processing Images ... {2} ", i, numberLoop, vectors.Count());
                    var figmaImageResponse = FigmaApiHelper.GetFigmaImages(File, vectors.Select(s => s.FigmaNode.id), imageFormat);
                    if (figmaImageResponse != null)
                    {
                        foreach (var image in figmaImageResponse.images)
                        {
                            if (image.Value == null)
                            {
                                continue;
                            }

                            var img = imageCacheResponse.FirstOrDefault(s => image.Value == s.Item1);
                            if (img?.Item1 != null)
                            {
                                img.Item2.Add(image.Key);
                            }
                            else
                            {
                                imageCacheResponse.Add(new Tuple <string, List <string> >(image.Value, new List <string>()
                                {
                                    image.Key
                                }));
                            }
                        }
                    }
                }

                //get images not dupplicates
                Console.WriteLine("Finished image to download {0}", images.Count);

                if (imageFormat == ImageQueryFormat.svg)
                {
                    //with all the keys now we get the dupplicated images
                    foreach (var imageUrl in imageCacheResponse)
                    {
                        var image = FigmaApiHelper.GetUrlContent(imageUrl.Item1);

                        foreach (var figmaNodeId in imageUrl.Item2)
                        {
                            var vector = imageFigmaNodes.FirstOrDefault(s => s.FigmaNode.id == figmaNodeId);
                            Console.Write("[{0}:{1}:{2}] {3}...", vector.FigmaNode.GetType(), vector.FigmaNode.id, vector.FigmaNode.name, imageUrl);

                            if (vector != null && vector.View is LiteForms.Graphics.ISvgShapeView imageView)
                            {
                                AppContext.Current.BeginInvoke(() => {
                                    imageView.Load(image);
                                });
                            }
                            Console.Write("OK \n");
                        }
                    }
                }
                else
                {
                    //with all the keys now we get the dupplicated images
                    foreach (var imageUrl in imageCacheResponse)
                    {
                        var Image = AppContext.Current.GetImage(imageUrl.Item1);
                        foreach (var figmaNodeId in imageUrl.Item2)
                        {
                            var vector = imageFigmaNodes.FirstOrDefault(s => s.FigmaNode.id == figmaNodeId);
                            Console.Write("[{0}:{1}:{2}] {3}...", vector.FigmaNode.GetType(), vector.FigmaNode.id, vector.FigmaNode.name, imageUrl);

                            if (vector != null)
                            {
                                AppContext.Current.BeginInvoke(() => {
                                    if (vector.View is IImageView imageView)
                                    {
                                        imageView.Image = Image;
                                    }
                                    else if (vector.View is IImageButton imageButton)
                                    {
                                        imageButton.Image = Image;
                                    }
                                });
                            }
                            Console.Write("OK \n");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }