Exemple #1
0
        private bool HandleGet(RequestEventArgs e, NetworkRequest req)
        {
            //No url?
            if (string.IsNullOrEmpty(req.Param))
            {
                return(false);
            }

            string[] possiblePaths;


            if (shareInfoService.ToLocalPath(req.Param, out possiblePaths))
            {
                foreach (string possiblePath in possiblePaths)
                {
                    if (File.Exists(possiblePath))
                    {
                        var ffu     = new FAPFileUploader(bufferService, serverUploadLimiterService);
                        var session = new TransferSession(ffu);
                        model.TransferSessions.Add(session);
                        try
                        {
                            //Try to find the username of the request
                            string userName = e.Context.RemoteEndPoint.Address.ToString();
                            Node   search   = model.Network.Nodes.ToList().Where(n => n.ID == req.SourceID).FirstOrDefault();
                            if (null != search && !string.IsNullOrEmpty(search.Nickname))
                            {
                                userName = search.Nickname;
                            }

                            using (
                                FileStream fs = File.Open(possiblePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                            {
                                ffu.DoUpload(e.Context, fs, userName, possiblePath);
                            }

                            //Add log of upload
                            double seconds = (DateTime.Now - ffu.TransferStart).TotalSeconds;
                            var    txlog   = new TransferLog();
                            txlog.Nickname  = userName;
                            txlog.Completed = DateTime.Now;
                            txlog.Filename  = Path.GetFileName(possiblePath);
                            txlog.Path      = Path.GetDirectoryName(req.Param);
                            if (!string.IsNullOrEmpty(txlog.Path))
                            {
                                txlog.Path = txlog.Path.Replace('\\', '/');
                                if (txlog.Path.StartsWith("/"))
                                {
                                    txlog.Path = txlog.Path.Substring(1);
                                }
                            }

                            txlog.Size = ffu.Length - ffu.ResumePoint;
                            if (txlog.Size < 0)
                            {
                                txlog.Size = 0;
                            }
                            if (0 != seconds)
                            {
                                txlog.Speed = (int)(txlog.Size / seconds);
                            }
                            model.CompletedUploads.Add(txlog);
                        }
                        finally
                        {
                            model.TransferSessions.Remove(session);
                        }
                        return(true);
                    }
                }
            }

            e.Response.Status = HttpStatusCode.NotFound;
            var generator = new ResponseWriter();

            generator.SendHeaders(e.Context, e.Response);
            return(true);
        }
Exemple #2
0
        public bool Handle(string req, RequestEventArgs e)
        {
            e.Response.Status = HttpStatusCode.OK;
            string path = Utility.DecodeURL(e.Request.Uri.AbsolutePath);

            byte[] data = null;

            if (path.StartsWith(WEB_ICON_PREFIX))
            {
                //what icon been requested?
                string ext = path.Substring(path.LastIndexOf("/") + 1);

                lock (sync)
                {
                    //Has the icon been requested already? if so just return that
                    if (iconCache.ContainsKey(ext))
                    {
                        data = iconCache[ext];
                        e.Response.ContentType = contentTypes["png"];
                    }
                    else
                    {
                        //item wasnt cached
                        if (ext == "folder")
                        {
                            data = GetResource("Images\\folder.png");
                            iconCache.Add("folder", data);
                            e.Response.ContentType = contentTypes["png"];
                        }
                        else
                        {
                            Icon icon = IconReader.GetFileIcon("file." + ext, IconReader.IconSize.Small, false);
                            using (var mem = new MemoryStream())
                            {
                                using (Bitmap bmp = icon.ToBitmap())
                                {
                                    bmp.MakeTransparent();
                                    bmp.Save(mem, ImageFormat.Png);
                                    data = mem.ToArray();
                                    iconCache.Add(ext, data);
                                    e.Response.ContentType = contentTypes["png"];
                                }
                            }
                        }
                    }
                }
            }
            else if (path.StartsWith(WEB_PREFIX))
            {
                //Has a static file been requested?

                data = GetResource(path.Substring(WEB_PREFIX.Length));

                string ext = Path.GetExtension(path);
                if (ext != null && ext.StartsWith("."))
                {
                    ext = ext.Substring(1);
                }

                ContentTypeHeader header;
                if (!contentTypes.TryGetValue(ext, out header))
                {
                    header = contentTypes["default"];
                }
                e.Response.ContentType = header;
            }
            else
            {
                bool validPath = false;

                string page     = Encoding.UTF8.GetString(GetResource("template.html"));
                var    pagedata = new Dictionary <string, object>();

                pagedata.Add("model", model);
                pagedata.Add("appver", Model.AppVersion);
                pagedata.Add("freelimit", Utility.FormatBytes(Model.FREE_FILE_LIMIT));
                pagedata.Add("uploadslots", model.MaxUploads);
                int freeslots = model.MaxUploads - uploadLimiter.GetActiveTokenCount();
                pagedata.Add("currentuploadslots", freeslots);
                pagedata.Add("queueInfo", freeslots > 0 ? "" : "  Queue length: " + uploadLimiter.GetQueueLength() + ".");
                pagedata.Add("slotcolour", freeslots > 0 ? "green" : "red");

                pagedata.Add("util", new Utility());

                if (!path.EndsWith("/"))
                {
                    pagedata.Add("path", (path + "/").Replace("#", "%23"));
                }
                else
                {
                    pagedata.Add("path", (path).Replace("#", "%23"));
                }

                //Add path info
                var paths = new List <Dictionary <string, object> >();

                string[] split = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < split.Length; i++)
                {
                    var sb = new StringBuilder("/");
                    for (int y = 0; y <= i; y++)
                    {
                        sb.Append(split[y]);
                        sb.Append("/");
                    }

                    var di = new Dictionary <string, object>();
                    di.Add("Name", split[i]);
                    di.Add("Path", sb.ToString());
                    paths.Add(di);
                }

                pagedata.Add("pathSplit", paths);

                /* List<DisplayInfo> peers = new List<DisplayInfo>();
                 *
                 * foreach (var peer in model.Network.Nodes.ToList().Where(n => n.NodeType != ClientType.Overlord && !string.IsNullOrEmpty(n.Nickname)))
                 * {
                 *   if (!string.IsNullOrEmpty(peer.Location))
                 *   {
                 *       DisplayInfo p = new DisplayInfo();
                 *       p.SetData("Name", string.IsNullOrEmpty(peer.Nickname) ? "Unknown" : peer.Nickname);
                 *       p.SetData("Location", peer.Location);
                 *       peers.Add(p);
                 *   }
                 * }
                 *
                 * pagedata.Add("peers", peers);*/
                var  files     = new List <Dictionary <string, object> >();
                long totalSize = 0;



                //Try to resolve the path to a file first
                string[] possiblePaths;
                if (infoService.ToLocalPath(path, out possiblePaths))
                {
                    //User has requested a file
                    foreach (string possiblePath in possiblePaths)
                    {
                        if (File.Exists(possiblePath))
                        {
                            return(SendFile(e, possiblePath, path));
                        }
                    }
                }

                //User didnt request a file so try to send directory info
                List <BrowsingFile> results;
                if (infoService.GetPath(path, false, true, out results))
                {
                    foreach (var browsingFile in results)
                    {
                        if (browsingFile.IsFolder)
                        {
                            var d = new Dictionary <string, object>
                            {
                                { "Name", browsingFile.Name },
                                { "Path", Utility.EncodeURL(browsingFile.Name) },
                                { "Icon", "folder" },
                                { "Sizetxt", Utility.FormatBytes(browsingFile.Size) },
                                { "Size", browsingFile.Size },
                                {
                                    "LastModifiedtxt",
                                    browsingFile.LastModified.ToShortDateString()
                                },
                                { "LastModified", browsingFile.LastModified }
                            };
                            files.Add(d);
                            totalSize += browsingFile.Size;
                        }
                        else
                        {
                            var d = new Dictionary <string, object> {
                                { "Name", browsingFile.Name }
                            };
                            string ext = Path.GetExtension(browsingFile.Name);
                            if (ext != null && ext.StartsWith("."))
                            {
                                ext = ext.Substring(1);
                            }
                            string name = browsingFile.Name;
                            if (!string.IsNullOrEmpty(name))
                            {
                                name = name.Replace("#", "%23");
                            }
                            d.Add("Path", name);
                            d.Add("Icon", ext);
                            d.Add("Size", browsingFile.Size);
                            d.Add("Sizetxt", Utility.FormatBytes(browsingFile.Size));
                            d.Add("LastModifiedtxt", browsingFile.LastModified.ToShortDateString());
                            d.Add("LastModified", browsingFile.LastModified);
                            files.Add(d);
                            totalSize += browsingFile.Size;
                        }
                    }

                    validPath = true;
                    //Clear result list to help GC
                    results.Clear();
                }


                pagedata.Add("files", files);
                pagedata.Add("totalSize", Utility.FormatBytes(totalSize));

                if (validPath)
                {
                    //Generate the page
                    page = TemplateEngineService.Generate(page, pagedata);
                    data = Encoding.UTF8.GetBytes(page);
                    e.Response.ContentType = contentTypes["html"];
                }

                //Clear up
                foreach (var item in pagedata.Values)
                {
                    if (item is Dictionary <string, object> )
                    {
                        var i = item as Dictionary <string, object>;
                        i.Clear();
                    }
                }
                pagedata.Clear();
            }

            if (null == data)
            {
                data = Encoding.UTF8.GetBytes("404 Not found");
            }
            var generator = new ResponseWriter();

            e.Response.ContentLength.Value = data.Length;
            generator.SendHeaders(e.Context, e.Response);
            e.Context.Stream.Write(data, 0, data.Length);
            e.Context.Stream.Flush();
            data = null;
            return(true);
        }