Ejemplo n.º 1
0
        public void HandleRequest(HttpListenerContext context)
        {
            var req  = context.Request;
            var resp = context.Response;

            try
            {
                if (!_mod.IsBeatSaberInstalled || !_mod.IsInstalledBeatSaberModded)
                {
                    resp.BadRequest("Modded Beat Saber is not installed!");
                    _showToast("Can't upload.", "Modded Beat Saber is not installed!");
                    return;
                }
                var ct = req.ContentType;
                if (!ct.StartsWith("multipart/form-data"))
                {
                    resp.BadRequest("Expected content-type of multipart/form-data");
                    return;
                }

                Dictionary <string, MemoryStream> files = new Dictionary <string, MemoryStream>();
                var parser = new HttpMultipartParser.StreamingMultipartFormDataParser(req.InputStream);
                parser.FileHandler = (name, fileName, type, disposition, buffer, bytes) =>
                {
                    if (name != "file")
                    {
                        Log.LogMsg($"Got extra form value named {name}, ignoring it");
                        return;
                    }
                    MemoryStream s = null;
                    if (files.ContainsKey(fileName))
                    {
                        s = files[fileName];
                    }
                    else
                    {
                        s = new MemoryStream();
                        files.Add(fileName, s);
                    }
                    s.Write(buffer, 0, bytes);
                };
                parser.Run();
                if (files.Count < 1)
                {
                    resp.BadRequest("Didn't get any useable files.");
                    return;
                }

                bool forceOverwrite = false;
                if (!string.IsNullOrWhiteSpace(req.Url.Query))
                {
                    foreach (string kvp in req.Url.Query.TrimStart('?').Split("&"))
                    {
                        var split = kvp.Split('=');
                        if (split.Count() < 1)
                        {
                            continue;
                        }
                        if (split[0].ToLower() == "overwrite")
                        {
                            forceOverwrite = true;
                            break;
                        }
                    }
                }

                foreach (var file in files.Keys.ToList())
                {
                    var    s = files[file];
                    byte[] b = s.ToArray();
                    files.Remove(file);
                    s.Dispose();
                    try
                    {
                        //TODO: duplicate code on determining file type with what's in file download... need another method in importmanager to determine file
                        if (file.ToLower().EndsWith("json") || file.ToLower().EndsWith("bplist"))
                        {
                            _getImportManager().ImportFile(file, "application/json", b);
                        }
                        else
                        {
                            MemoryStream ms = new MemoryStream(b);
                            try
                            {
                                var provider = new ZipFileProvider(ms, file, FileCacheMode.None, true, QuestomAssets.Utils.FileUtils.GetTempDirectory());
                                try
                                {
                                    _getImportManager().ImportFromFileProvider(provider, () =>
                                    {
                                        provider.Dispose();
                                        ms.Dispose();
                                    }, overwriteIfExists: forceOverwrite);
                                }
                                catch
                                {
                                    provider.Dispose();
                                    throw;
                                }
                            }
                            catch
                            {
                                ms.Dispose();
                                throw;
                            }
                        }
                    }
                    catch (ImportException iex)
                    {
                        _showToast($"Unable to import file", $"There was an error importing the file {file}: {iex.FriendlyMessage}", ClientModels.ToastType.Error, 5);
                    }
                    catch (Exception ex)
                    {
                        _showToast($"Unable to process file", $"There was an error processing the file {file}.", ClientModels.ToastType.Error, 5);
                    }
                }
                resp.Ok();
            }
            catch (Exception ex)
            {
                Log.LogErr("Exception handling mod install step 1!", ex);
                resp.StatusCode = 500;
            }
        }
Ejemplo n.º 2
0
        public TResult <bool> UploadRedLinesAddiotionalFiles(string filename, System.IO.Stream stream)
        {
            System.Diagnostics.Debug.Assert(false);
            try
            {
                string user        = System.Web.HttpContext.Current.Request.Headers["user"];
                string project     = System.Web.HttpContext.Current.Request.Headers["projectname"];
                string layer       = System.Web.HttpContext.Current.Request.Headers["layer"];
                string uid         = System.Web.HttpContext.Current.Request.Headers["owner"];
                string description = System.Web.HttpContext.Current.Request.Headers["description"];
                string extension   = System.Web.HttpContext.Current.Request.Headers["extension"];

                LogHandler.WriteLog("Service.cs: UploadRedLinesAddiotionalFiles.  : Starting" + filename, EventLogEntryType.Information);
                //var parser = new HttpMultipartParser.MultipartFormDataParser(stream);
                var parser = new HttpMultipartParser.StreamingMultipartFormDataParser(stream);
                parser.ParameterHandler += parameter => { };
                // Write the part of the file we've recieved to a file stream. (Or do something else)

                filename = filename + "." + extension;
                LogHandler.WriteLog("Service.cs: UploadRedLinesAddiotionalFiles.  : Creating File " + filename, EventLogEntryType.Information);
                var write = File.OpenWrite("c:\\temp\\" + filename);


                //object comosobject = System.Web.HttpContext.Current.ApplicationInstance.Application["ComosAPI"];
                //IBRServiceContracts.IServiceContract m_ComosAPIService = (IBRServiceContracts.IServiceContract)comosobject;
                IServiceContract m_ComosAPIService = GetComosAPI();


                parser.FileHandler += (name, fileName, type, disposition, buffer, bytes) =>
                {
                    LogHandler.WriteLog("   Service.cs: UploadRedLinesAddiotionalFiles.  : Write block to File " + filename, EventLogEntryType.Information);
                    write.Write(buffer, 0, bytes);
                };
                parser.StreamClosedHandler += () =>
                {
                    LogHandler.WriteLog("   Service.cs: UploadRedLinesAddiotionalFiles.  :  File stream closed" + filename, EventLogEntryType.Information);
                    // Do things when my input stream is closed
                    write.Flush();
                    write.Close();
                    write.Dispose();

                    using (var reader = System.IO.File.OpenRead("c:\\temp\\" + filename))
                    {
                        RemoteFileInfo fileInfo = new RemoteFileInfo()
                        {
                            FileByteStream = reader,
                            Project        = project,
                            User           = user,
                            Owner          = uid,
                            Workinglayer   = layer,
                            FileName       = filename,
                            Extension      = extension,
                            Description    = description,
                        };
                        m_ComosAPIService.CreateRedLinesAndAditionalDocuments(fileInfo);
                    }
                };
                parser.Run();
            }
            catch (Exception ex)
            {
                LogHandler.WriteLog("Service.cs: UploadRedLinesAddiotionalFiles.  : Exception = " + ex.Message, EventLogEntryType.Error);

                return(new TResult <bool>()
                {
                    Status = false,
                    Message = ex.Message,
                    data = false
                });
            }
            //return null;
            return(new TResult <bool>()
            {
                data = true,
                Status = true,
            });
        }