public object Delete(ImageRequest request)
        {
            Database.Db.Delete <Image>(x => x.Id == request.Id);

            FileInfo fi = UploadService.GetFileInfo(request.Id);

            if (fi != null)
            {
                fi.Delete();
            }

            DirectoryInfo di = FileCache.GetCacheDir();

            FileInfo[] cachefiles = di.GetFiles(request.Id.ToString().Replace("-", "") + "*");
            foreach (var f in cachefiles)
            {
                f.Delete();
            }
            return(new HttpResult(System.Net.HttpStatusCode.OK, "File deleted."));
        }
        static void ConvertImage(Image img)
        {
            foreach (int w in ImageService.ResizeWidths)
            {
                if (img.Width > w)
                {
                    int h3 = (int)((double)img.Height / (double)img.Width * (double)w);
                    if (h3 % 2 == 1)
                    {
                        h3 -= 1;
                    }
                    var file = UploadService.GetFileInfo(img.Id);
                    if (file == null)
                    {
                        Console.WriteLine("???");
                        continue;
                    }

                    string output = Path.Combine(FileCache.GetCacheDir().FullName, img.Id + DownSite.Constants.Seperator + w + "x0" + ".jpg");

                    if (File.Exists(output))
                    {
                        continue;
                    }

                    int h2 = h3;
                    int w2 = w;
                    Console.WriteLine("converting image to " + w2 + "x" + h2);
                    using (var bmp = new Bitmap(file.FullName))
                    {
                        using (var resized = resizeImage(bmp, new Size(w2, h2)))
                        {
                            ImageService.SaveJpeg(resized, output);
                        }
                    }
                }
            }
        }
        static HttpResult ResizeHelper(ImageRequest request, Image img, int[] sizes, Func <int, string> x)
        {
            foreach (var h in sizes)
            {
                string tmp = x(h);
                if (request.Param.Contains(tmp))
                {
                    string extension = null;
                    string mimetype  = null;
                    string end       = DownSite.Constants.Seperator + tmp;
                    if (img.MimeType.StartsWith("video"))
                    {
                        extension = "mp4";
                        mimetype  = "video/mp4";
                    }
                    else if (img.MimeType.StartsWith("image"))
                    {
                        extension = "jpg";
                        mimetype  = "image/jpg";
                    }

                    if (extension != null)
                    {
                        var file = FileCache.GetFile(img.Id + end + "." + extension);
                        if (file != null)
                        {
                            return(new HttpResult(file, mimetype)
                            {
                            });
                        }
                    }
                }
            }

            return(null);
        }
        static void ConvertVideo(Image img)
        {
            foreach (int h in ImageService.ResizeHeights)
            {
                if (img.Height > h)
                {
                    int w = (int)((double)img.Width / (double)img.Height * (double)h);
                    if (w % 2 == 1)
                    {
                        w -= 1;
                    }
                    var file = UploadService.GetFileInfo(img.Id);
                    if (file == null)
                    {
                        Console.WriteLine("???");
                        continue;
                    }

                    string output = Path.Combine(FileCache.GetCacheDir().FullName, img.Id + DownSite.Constants.Seperator + "0x" + h + ".mp4");

                    if (File.Exists(output))
                    {
                        continue;
                    }

                    if (ConvertQueue.Any(x => x.Output == output))
                    {
                        Console.WriteLine("already in convert queue: " + output);
                        continue;
                    }

                    Console.WriteLine("add to convert queue: " + output);
                    ConvertQueue.Add(new ConvertInfo(w, h, img, output, file));
                }
            }
        }
        static void Main(string[] args)
        {
            string output = "output";
            string data   = "data";
            //string web = new FileInfo(Assembly.GetEntryAssembly().Location).Directory.FullName;
            string web    = "web";
            string watch  = "watch";
            bool   delete = false;

            int i = Array.IndexOf(args, "--output");

            if (i >= 0)
            {
                output = args[i + 1];
            }

            i = Array.IndexOf(args, "--data");
            if (i >= 0)
            {
                data = args[i + 1];
            }

            i = Array.IndexOf(args, "--web");
            if (i >= 0)
            {
                web = args[i + 1];
            }

            i = Array.IndexOf(args, "--delete");
            if (i >= 0)
            {
                delete = bool.Parse(args[i + 1]);
            }

            i = Array.IndexOf(args, "--watch");
            if (i >= 0)
            {
                watch = args[i + 1];
            }

            data   = new DirectoryInfo(data).FullName;
            web    = new DirectoryInfo(web).FullName;
            output = new DirectoryInfo(output).FullName;
            watch  = new DirectoryInfo(watch).FullName;

            Paths.Web               = web;
            Paths.Data              = data;
            Paths.Output            = output;
            Paths.Watch             = watch;
            GeneratorService.Delete = delete;

            Database.Init();

            bool gen_cache = !FileCache.CacheDirExists();

            Console.WriteLine("Data directory: {0}", data);
            Console.WriteLine("Web directory: {0}", web);
            Console.WriteLine("Output directory: {0}", output);

            if (Directory.Exists(watch))
            {
                Console.WriteLine("Watch directory: {0}", watch);
                Watcher.Init(watch);
            }

            var appHost = new DownSiteAppHost(web);


            /*
             * var pathProviders = new List<IVirtualPathProvider> {
             *  new FileSystemVirtualPathProvider(appHost, appHost.Config.WebHostPhysicalPath),
             *  new FileSystemVirtualPathProvider(appHost, appHost.Config.WebHostPhysicalPath)
             * };
             *
             * appHost.VirtualPathProvider = pathProviders.Count > 1
             *  ? new MultiVirtualPathProvider(appHost, pathProviders.ToArray())
             *  : pathProviders.First();*/



            appHost.Init();
            appHost.Start(BaseUri);
            Console.WriteLine("Listening on " + BaseUri);


            if (gen_cache)
            {
                Console.WriteLine("Generating image cache...");
                Image.GenerateCache();
                Console.WriteLine("done.");
            }

            string line;

            do
            {
                Console.WriteLine("Press return to generate the page");
                line = Console.ReadLine();
                if (line.Length == 0)
                {
                    Static.Generate(output, data, delete);
                }
            }while (line.Length == 0);
        }
        public object Get(ImageRequest request)
        {
            var img = Image.Load(request.Id);

            if (img != null)
            {
                bool thumb3 = request.Param.Contains("thumb");

                if (!thumb3)
                {
                    var res = ResizeHelper(request, img.Item1, ResizeHeights, x => "0x" + x);
                    if (res != null)
                    {
                        return(res);
                    }
                    res = ResizeHelper(request, img.Item1, ResizeWidths, x => x + "x0");
                    if (res != null)
                    {
                        return(res);
                    }
                }

                if (thumb3)
                {
                    string filename_without_extension = Path.GetFileNameWithoutExtension(img.Item2.Name);
                    string thumb      = filename_without_extension + DownSite.Constants.Seperator + "thumb.jpg";
                    var    thumb_file = FileCache.GetFile(thumb);
                    if (thumb_file != null)
                    {
                        return(new HttpResult(thumb_file, MimeTypes.ImageJpg)
                        {
                        });
                    }

                    thumb_file = new FileInfo(Path.Combine(FileCache.GetCacheDir().FullName, thumb));

                    var mimetypes = new string[] { MimeTypes.ImageJpg, MimeTypes.ImagePng, MimeTypes.ImageGif };

                    if (!mimetypes.Contains(img.Item1.MimeType))
                    {
                        if (VideoThumbnailer.MakeThumbnail(img.Item2.FullName, thumb_file.FullName))
                        {
                            return(new HttpResult(thumb_file, MimeTypes.ImageJpg)
                            {
                            });
                        }
                        else
                        {
                            return(new HttpResult(System.Net.HttpStatusCode.NotFound, string.Format("No thumbnails for type {0}.", img.Item1.MimeType)));
                        }
                    }
                    else
                    {
                        using (var fs = img.Item2.OpenRead())
                        {
                            using (Bitmap bmp = new Bitmap(fs))
                            {
                                using (var thumb2 = bmp.GetThumbnailImage(80, 80, null, IntPtr.Zero))
                                {
                                    SaveJpeg(thumb2, thumb_file.FullName);
                                    return(new HttpResult(thumb_file, MimeTypes.ImageJpg)
                                    {
                                    });
                                }
                            }
                        }
                    }
                }
                else
                {
                    var res = new HttpResult(img.Item2, string.IsNullOrWhiteSpace(img.Item1.MimeType) ? MimeTypes.ImageJpg : img.Item1.MimeType)
                    {
                    };
                    if (img.Item1.MimeType == "application/octet-stream")
                    {
                        res.Options.Add("Content-Disposition", "attachment; filename=\"" + img.Item1.FileName + "\"");
                    }
                    return(res);
                }
            }
            return(new HttpResult(System.Net.HttpStatusCode.NotFound, "No image with that ID."));
        }
Exemple #7
0
        public static void Init()
        {
            string dbfile = Path.Combine(Paths.Data, "db.sqlite3");
            bool   init   = !File.Exists(dbfile);

            if (init)
            {
                if (Directory.Exists(Paths.Data))
                {
                    Directory.Delete(Paths.Data, true);
                }
                var dir = Directory.CreateDirectory(Paths.Data);
                dir.CreateSubdirectory("files");
                dir.CreateSubdirectory("cache");

                Db = Database.OpenDbConnection(dbfile);
                Db.CreateTable <User>(true);
                Db.CreateTable <Image>(true);
                Db.CreateTable <Article>(true);
                Db.CreateTable <Tag>(true);
                Db.CreateTable <Settings>(true);
                Db.CreateTable <Configuration>(true);
                Db.CreateTable <Comment>(true);
                Db.CreateTable <Menu>(true);

                Db.Insert <Configuration>(new Configuration()
                {
                    Id = Guid.Empty, Version = Version
                });
                Db.Insert <Settings>(new Settings()
                {
                    Id = Guid.Empty, DisqusShortName = "", SiteName = "DownSite", ShowComments = true, AllowWriteComments = true, ShowLogin = false, ArticlesPerPage = 10, SiteDescription = "Test", SiteUrl = ""
                });

                Db.ExecuteSql(@"CREATE UNIQUE INDEX tag_unique on Tag(ArticleId, Name);");


                Guid     pic1 = Guid.NewGuid(), pic2 = Guid.NewGuid(), pic3 = Guid.NewGuid();
                FileInfo tmp = new FileInfo(Path.Combine(Paths.Web, "acf7eede5be5aa69.jpg"));
                if (tmp.Exists)
                {
                    Image.Save(pic1, Db, MimeTypes.ImageJpg, tmp.Name, tmp.OpenRead());
                }
                tmp = new FileInfo(Path.Combine(Paths.Web, "e3939e928899550f.jpg"));
                if (tmp.Exists)
                {
                    Image.Save(pic2, Db, MimeTypes.ImageJpg, tmp.Name, tmp.OpenRead());
                }
                tmp = new FileInfo(Path.Combine(Paths.Web, "d552c86d2ebd373c.webm"));
                if (tmp.Exists)
                {
                    Image.Save(pic3, Db, "video/webm", tmp.Name, tmp.OpenRead());
                }

                Guid person1;
                Db.Insert <User>(new User()
                {
                    Id = person1 = Guid.NewGuid(), UserName = "******", Password = Util.SHA1("downsite"), FirstName = "Firstname", LastName = "Lastname"
                });
                Db.Insert <User>(new User()
                {
                    Id = Guid.NewGuid(), UserName = "******", FirstName = "cody1", LastName = "test"
                });
                Db.Insert <User>(new User()
                {
                    Id = Guid.NewGuid(), UserName = "******", FirstName = "cody2", LastName = "test"
                });

                string content = string.Format(@"-CONTENT-

![](/image/{0})
![video](/image/{1})
![youtube](cxBcHLylFbw)", pic1.ToString().Replace("-", "") + ".jpg", pic3.ToString().Replace("-", "") + ".webm");

                Guid article;
                Db.Insert <Article>(new Article()
                {
                    Id = article = Guid.NewGuid(), ShowInBlog = true, Content = content, AuthorId = person1, Created = DateTime.Now, Title = "page1", VersionGroup = Guid.NewGuid()
                });

                Db.Insert <Tag>(new Tag()
                {
                    ArticleId = article, Name = "a"
                });
                Db.Insert <Tag>(new Tag()
                {
                    ArticleId = article, Name = "b"
                });
                Db.Insert <Tag>(new Tag()
                {
                    ArticleId = article, Name = "c"
                });


                Db.Insert <Article>(new Article()
                {
                    Id           = Guid.NewGuid(),
                    AuthorId     = person1,
                    ShowInMenu   = true,
                    Content      = @"#MenuItem 1

<pre><code>blablalb
rhgb
regj
rejgn
</code></pre>",
                    Created      = DateTime.Now,
                    Title        = "MenuItem 1",
                    VersionGroup = Guid.NewGuid()
                });
                Db.Insert <Article>(new Article()
                {
                    Id = Guid.NewGuid(), AuthorId = person1, ShowInMenu = true, Content = "#MenuItem 2", Created = DateTime.Now, Title = "MenuItem 2", VersionGroup = Guid.NewGuid()
                });

                for (int i = 0; i < 20; ++i)
                {
                    Guid id;
                    Db.Insert <Article>(new Article()
                    {
                        Id = id = Guid.NewGuid(), AuthorId = person1, ShowInBlog = true, Content = "blog" + i, Created = DateTime.Now, Title = "blog" + i, VersionGroup = Guid.NewGuid()
                    });
                    Db.Insert <Tag>(new Tag()
                    {
                        ArticleId = id, Name = "c"
                    });
                }

                Db.Insert <Comment>(new Comment()
                {
                    Id = Guid.NewGuid(), ArticleId = article, Content = "blabla1", Created = DateTime.Now, Name = "anon"
                });
                Db.Insert <Comment>(new Comment()
                {
                    Id = Guid.NewGuid(), ArticleId = article, Content = "blabla2", Created = DateTime.Now, Name = "anon"
                });

                Db.Insert <Menu>(new Menu()
                {
                    Id = Guid.NewGuid(), Caption = "Blog", Link = "/blog/page1.html"
                });

                var a = Db.LoadSingleById <Article>(article);
                if (a.Category == null)
                {
                    throw new Exception("BUG");
                }
                a = Db.LoadSelect <Article>(y => y.Id == article).First();
                if (a.Category == null)
                {
                    throw new Exception("BUG");
                }
            }
            else
            {
                Db = Database.OpenDbConnection(dbfile);

                int version = Configuration.Load().Version;
                if (version < Version)
                {
                    Migrate(version, Version);
                }
                else if (version > Version)
                {
                    throw new Exception(string.Format("Database version too high. ({0} vs. {1})", version, Version));
                }
            }

            if (FileCache.CacheDirExists())
            {
                foreach (var f in FileCache.GetCacheDir().GetFiles("*.tmp"))
                {
                    try
                    {
                        f.Delete();
                    }
                    catch
                    {
                    }
                }
            }
        }