public override void OnOperation(HttpListenerContext context, Authentication authentication) { HttpMultipartParser httpMultipartParser = new HttpMultipartParser(context.Request.InputStream, "file"); if (!httpMultipartParser.Success) { Utils.SendErrorPage(context.Response, "Invalid request", true, HttpStatusCode.BadRequest); return; } if (!authentication.IsSignedIn) { Utils.SendErrorPage(context.Response, "You are not signed in.", true, HttpStatusCode.Unauthorized); return; } if (!authentication.HasAtLeastAuthenticationLevel(Users.AuthenticationLevel.VerifiedUser)) { Utils.SendErrorPage(context.Response, "You have to link a clone drone account to your account to upload mods, this is to prevent people from getting around bans.", true, HttpStatusCode.Unauthorized); return; } string sessionId = authentication.SessionID; ModInfo modInfo; if (!UploadedModsManager.Instance.TryUploadModFromZip(httpMultipartParser.FileContents, sessionId, out modInfo, out string error)) { Utils.SendErrorPage(context.Response, error, true, HttpStatusCode.InternalServerError); return; } Utils.SendErrorPage(context.Response, "Uploaded Mod!", false, HttpStatusCode.OK); }
public Contest PostContest() { Contest contest; var reqo = Request.Content.ReadAsStreamAsync().Result; HttpMultipartParser parser = new HttpMultipartParser(reqo); var contestJON = parser.Parameters["contest"]; if (contestJON == null) { throw new HttpResponseException(new HttpResponseMessage() { Content = new StringContent("No contest parameter") }); } contest = JsonConvert.DeserializeObject <Contest>(contestJON, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); contest.ProductPhotos = parser.Files.Where(x => x.Key.StartsWith("ProductPhotos")).Select(x => x.Value).ToList(); contest.ExamplePhotos = parser.Files.Where(x => x.Key.StartsWith("ExamplePhotos")).Select(x => x.Value).ToList(); ModelState.Clear(); contest.UserId = UserId; if (contest.Id == null) { contest.Id = Guid.NewGuid().ToString(); } Validate(contest); if (!ModelState.IsValid) { throw new HttpResponseException(new HttpResponseMessage() { Content = new ObjectContent(ModelState.GetType(), ModelState, this.Configuration.Formatters.JsonFormatter) }); } db.Contests.Add(contest); try { db.SaveChanges(); } catch (DbUpdateException) { if (ContestExists(contest.Id)) { throw new HttpResponseException(HttpStatusCode.Conflict); } else { throw; } } return(contest); }
public void PostByImage() { var reqo = Request.Content.ReadAsStreamAsync().Result; HttpMultipartParser parser = new HttpMultipartParser(reqo); if (!parser.Success) { throw new HttpResponseException(HttpStatusCode.BadRequest); } var post = new Post(); post.ContestId = parser.Parameters["ContestId"]; post.HashTags = parser.Parameters["Hashtags"]; post.Id = Guid.NewGuid().ToString(); post.PostStatus = PostStatus.Pending; post.Photos = parser.Files.Select(x => x.Value).ToList(); post.SocialMedium = SocialMedia.Facebook; post.Text = parser.Parameters["caption"]; post.PlaceId = parser.Parameters["PlaceId"]; post.UserId = UserId; ModelState.Clear(); Validate(post); if (!ModelState.IsValid) { throw new HttpResponseException(new HttpResponseMessage() { Content = new ObjectContent(ModelState.GetType(), ModelState, this.Configuration.Formatters.JsonFormatter) }); } db.Posts.Add(post); try { db.SaveChanges(); sendEmailAboutPostVerification(post); } catch (DbUpdateException) { if (PostExists(post.Id)) { throw new HttpResponseException(HttpStatusCode.Conflict); } else { throw; } } }
public IHttpActionResult Upload(Stream stream) { HttpMultipartParser parser = new HttpMultipartParser(stream, "file"); if (parser.Success) { //string user = HttpUtility.UrlDecode(parser.Parameters["user"]); //string title = HttpUtility.UrlDecode(parser.Parameters["title"]); // Save the file somewhere File.WriteAllBytes(HttpContext.Current.Server.MapPath("~/DataImages") + "/ss.jpg", parser.FileContents); } return(Ok("Done")); }
public List <WCFTemplate> ImportTemplates(Stream file) { List <WCFTemplate> returnTemplateList = new List <WCFTemplate>(); try { HttpMultipartParser parser = new HttpMultipartParser(file, "file"); if (parser.Success) { string authenticationCookie = parser.Parameters["auth"]; string userName = ServiceUtils.Authorize(authenticationCookie, PermissionsTable.Instance.CanImportTemplates); if (parser.FileContents.Length > 0) { string jsonString = Misc.ToString(parser.FileContents); DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List <WCFTemplate>)); using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString))) { List <WCFTemplate> templates = serializer.ReadObject(ms) as List <WCFTemplate>; if (templates != null) { foreach (WCFTemplate template in templates) { UpdateTemplateIds(template); _addin.UpdateTemplate(userName, template, string.Empty); } } return(templates); } } } } catch (ServiceAuthorizationException) { returnTemplateList = GetImportTemplatesError("Access denied, please login with different user to have this feature available."); // throw new ServiceAuthorizationException("Access denied, please login with different user to have this feature available."); } catch (Exception e) { returnTemplateList = GetImportTemplatesError(e.Message); } return(returnTemplateList); }
public override void OnOperation(HttpListenerContext context, Authentication authentication) { HttpMultipartParser httpMultipartParser = new HttpMultipartParser(context.Request.InputStream, "file"); if (!httpMultipartParser.Success) { Utils.SendErrorPage(context.Response, "Invalid request", true, HttpStatusCode.BadRequest); return; } if (!authentication.IsSignedIn) { Utils.SendErrorPage(context.Response, "You are not signed in.", true, HttpStatusCode.Unauthorized); return; } string extension = Path.GetExtension(httpMultipartParser.Filename); byte[] imageData = httpMultipartParser.FileContents; if (!_validFileExtensions.Contains(extension.ToLower())) { Utils.SendErrorPage(context.Response, string.Format("The format \"{0}\" is not supported", extension), true, HttpStatusCode.BadRequest); return; } string path = UserManager.Instance.ProfilePicturesPath + authentication.UserID; foreach (string ext in _validFileExtensions) { string ph = path + ext; if (File.Exists(ph)) { File.Delete(ph); } } File.WriteAllBytes(path + extension, imageData); GetProfilePictureOperation.ClearImageCache(); Utils.SendErrorPage(context.Response, "Uploaded profile picture!", false, HttpStatusCode.OK); }
protected override void HandleRequest() { HttpMultipartParser parser = new HttpMultipartParser(Context.Request.InputStream, "data"); if (parser.Success) { using (var db = new Database(Program.Settings.GetValue("conn"))) { Account acc = db.Verify(parser.Parameters["guid"], parser.Parameters["password"]); var cmd = db.CreateQuery(); var guid = parser.Parameters["guid"]; if (guid == "Admin" && !acc.Admin) { guid = "Guest"; } if (parser.Parameters["admin"] == "true" && acc.Admin) { guid = "Admin"; } cmd.CommandText = "INSERT INTO sprites(guid, name, dataType, tags, data, fileSize) VALUES(@guid, @name, @dataType, @tags, @data, @fileSize)"; cmd.Parameters.AddWithValue("@guid", guid); cmd.Parameters.AddWithValue("@name", parser.Parameters["name"]); cmd.Parameters.AddWithValue("@dataType", parser.Parameters["datatype"]); cmd.Parameters.AddWithValue("@tags", parser.Parameters["tags"].Replace(", ", ",").Replace(" ,", ",").Trim()); cmd.Parameters.AddWithValue("@data", parser.FileContents); cmd.Parameters.AddWithValue("@fileSize", parser.FileContents.Length); try { var status = Encoding.UTF8.GetBytes(cmd.ExecuteNonQuery() > 0 ? "<Success/>" : "<Error>Account credentials not valid</Error>"); Context.Response.OutputStream.Write(status, 0, status.Length); } catch (Exception e) { Console.WriteLine(e); } } } }
public IHttpActionResult UploadFile() { try { if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); } var stream = Request.Content.ReadAsStreamAsync().Result; var parser = new HttpMultipartParser(stream, "file"); if (!parser.Success) { throw new HttpException(400, $"ProtoCMS: can't parse upload file request."); } var targetPath = HttpUtility.UrlDecode(parser.Parameters["targetPath"]); var fileStream = new MemoryStream(parser.FileContents); var handler = _fileMgr.GetHandler(); var result = handler.CreateFile(targetPath, fileStream); return(JsonProto(result)); } catch (HttpException hexc) { throw RestfulApiError(hexc); } }
public override void HandleRequest(HttpListenerContext context) { NameValueCollection query; //using (var rdr = new StreamReader(context.Request.InputStream)) // query = HttpUtility.ParseQueryString(rdr.ReadToEnd()); HttpMultipartParser parser = new HttpMultipartParser(context.Request.InputStream, "data"); byte[] status; //if (query.AllKeys.Length == 0) //{ // string queryString = string.Empty; // string currUrl = context.Request.RawUrl; // int iqs = currUrl.IndexOf('?'); // if (iqs >= 0) // { // query = // HttpUtility.ParseQueryString((iqs < currUrl.Length - 1) // ? currUrl.Substring(iqs + 1) // : String.Empty); // } //} if (parser.Success) { using (var db = new Database(Program.Settings.GetValue("conn"))) { Account acc = db.Verify(parser.Parameters["guid"], parser.Parameters["password"]); var cmd = db.CreateQuery(); var guid = parser.Parameters["guid"]; if (guid == "Admin" && !acc.Admin) { guid = "Guest"; } if (parser.Parameters["admin"] == "true" && acc.Admin) { guid = "Admin"; } cmd.CommandText = "INSERT INTO sprites(guid, name, dataType, tags, data, fileSize) VALUES(@guid, @name, @dataType, @tags, @data, @fileSize)"; cmd.Parameters.AddWithValue("@guid", guid); cmd.Parameters.AddWithValue("@name", parser.Parameters["name"]); cmd.Parameters.AddWithValue("@dataType", parser.Parameters["datatype"]); cmd.Parameters.AddWithValue("@tags", parser.Parameters["tags"].Replace(", ", ",").Replace(" ,", ",").Trim()); cmd.Parameters.AddWithValue("@data", parser.FileContents); cmd.Parameters.AddWithValue("@fileSize", parser.FileContents.Length); try { if (cmd.ExecuteNonQuery() > 0) { status = Encoding.UTF8.GetBytes("<Success/>"); } else { status = Encoding.UTF8.GetBytes("<Error>Account credentials not valid</Error>"); } context.Response.OutputStream.Write(status, 0, status.Length); } catch (Exception e) { Console.WriteLine(e); } } } }
public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { // path = /wifi/... //m_log.DebugFormat("[Wifi]: path = {0}", path); //m_log.DebugFormat("[Wifi]: ip address = {0}", httpRequest.RemoteIPEndPoint); //foreach (object o in httpRequest.Query.Keys) // m_log.DebugFormat(" >> {0}={1}", o, httpRequest.Query[o]); httpResponse.ContentType = "text/html"; string resource = GetParam(path); //m_log.DebugFormat("[INVENTORY HANDLER POST]: resource {0}", resource); Request request = RequestFactory.CreateRequest(string.Empty, httpRequest, Localization.GetLanguageInfo(httpRequest.Headers.Get("accept-language"))); Environment env = new Environment(request); string result = string.Empty; if (resource.Equals("/") || resource.Equals(string.Empty)) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); Dictionary <string, object> postdata = ServerUtils.ParseQueryString(body); string action = postdata.Keys.FirstOrDefault(key => key.StartsWith("action-")); if (action == null) { action = string.Empty; } else { action = action.Substring("action-".Length); } string folder = string.Empty; string newFolderName = string.Empty; List <string> nodes = new List <string>(); List <string> types = new List <string>(); if (postdata.ContainsKey("folder")) { folder = postdata["folder"].ToString(); } if (postdata.ContainsKey("newFolderName")) { newFolderName = postdata["newFolderName"].ToString(); } foreach (KeyValuePair <string, object> kvp in postdata) { if (kvp.Key.StartsWith("inv-")) { nodes.Add(kvp.Key.Substring(4)); types.Add(kvp.Value.ToString()); } } result = m_WebApp.Services.InventoryPostRequest(env, action, folder, newFolderName, nodes, types); } else if (resource.StartsWith("/upload")) { HttpMultipartParser parser = new HttpMultipartParser(requestData, "datafile"); if (parser.Success) { //string user = HttpUtility.UrlDecode(parser.Parameters["user"]); if (!Directory.Exists(WebAppUtils.UploadPath)) { Directory.CreateDirectory(WebAppUtils.UploadPath); } string filename = new Guid().ToString().Substring(0, 8) + ".iar"; string pathToFile = System.IO.Path.Combine(WebAppUtils.UploadPath, filename); if (File.Exists(pathToFile)) { File.Delete(pathToFile); } using (FileStream w = new FileStream(pathToFile, FileMode.CreateNew)) { w.Write(parser.FileContents, 0, parser.FileContents.Length); } result = m_WebApp.Services.InventoryUploadRequest(env, pathToFile); File.Delete(pathToFile); } } return(WebAppUtils.StringToBytes(result)); }