Ejemplo n.º 1
0
        public async Task <IActionResult> AddFile([FromForm] FileForAddDto fileForAddDto)
        {
            var file = fileForAddDto.File;

            fileForAddDto.TypeId = 2;
            var fileToCreate = _mapper.Map <File>(fileForAddDto);

            _repo.Add(fileToCreate);
            await _repo.SaveAll();

            int idOfFileAdded = _repo.GetFileMaxID();

            if (file != null)
            {
                string newFileName = idOfFileAdded + "_" + file.FileName;
                string path        = Path.Combine(_hostingEnv.ContentRootPath, "Upload/File", newFileName);
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    file.CopyTo(stream);
                    fileForAddDto.Url = newFileName;
                    fileToCreate.Url  = fileForAddDto.Url;
                    //_data.Entry(fileForAddDto).Property(x => x.Image).IsModified = true;
                    var fileFromRepo1 = await _repo.GetFile(idOfFileAdded);

                    _mapper.Map(fileToCreate, fileFromRepo1);
                    await _repo.SaveAll();
                }
            }
            fileToCreate.Url = BaseURL.GetBaseUrl(Request) + "/Upload/File/" + fileForAddDto.Url;
            return(CreatedAtRoute("GetFile", new { id = idOfFileAdded }, fileToCreate));
        }
Ejemplo n.º 2
0
        public static async Task <List <ScoreInfo> > GetUserRecent(string user, UsernameType?type = null, Mode?mode = null, int?limit = null)
        {
            QueueSize++;
            lock (Lock)
            {
                if (RateLimitPerMin > 0)
                {
                    int delay = (60000 + RateLimitPerMin - 1) / RateLimitPerMin;
                    Thread.Sleep(delay);
                }
            }
            QueueSize--;

            var call = BaseURL
                       .AppendPathSegment("get_user_recent")
                       .SetQueryParam("k", Key)
                       .SetQueryParam("u", user);

            if (type != null)
            {
                call.SetQueryParam("type", type);
            }
            if (mode != null)
            {
                call.SetQueryParam("m", mode);
            }
            if (limit != null)
            {
                call.SetQueryParam("limit", limit);
            }

            return(await call
                   .GetAsync()
                   .ReceiveJson <List <ScoreInfo> >());
        }
Ejemplo n.º 3
0
        /* Since Folha broke the custom date search, we started to use the automatic filter
         * private string FormatSeachDate()
         * {
         *  DateTime thisDay = DateTime.Today;
         *  string Today = thisDay.ToString("d");
         *  string PastDate = thisDay.AddDays(-2).ToString("d");
         *  string FormattedDate = PastDate + "&sd=&ed=" + Today;
         *
         *  return FormattedDate.Replace("/", "%2F");
         *
         * }
         */
        public override void search(string vKeyword)
        {
            Console.WriteLine("Iniciando busca Folha de SP");

            try
            {
                string vWord = BaseURL.Replace("KEYWORD", prepareKeyword(vKeyword));
                Document = Page.Load(vWord);
                Console.WriteLine("Selecionando resultados");

                /*When the search can't find the keyword, it offers related searchs and show us a message with related words
                 * wich is shown on a div with a "message info" class. Since related searchs are not interesting for us,
                 * we skip the search
                 */
                if (!hasMessage_info(Document))
                {
                    var vDivNodes = Document.DocumentNode.SelectNodes("//div[@class='c-headline__content']");
                    if (vDivNodes != null)
                    {
                        searchListResults(vDivNodes, vKeyword);
                    }
                }
                else
                {
                    Console.WriteLine("Palavra chave não encontrada, pulando resultados relacionados");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Erro -> {0}", e.Message);
                FLog.writeLog("Erro na palavra chave " + vKeyword + " na folha de SP");
                FLog.writeLog("Descrição do erro: " + e.Message);
                FLog.writeLog(" ");
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// List the Poppulo Accounts
        /// </summary>
        /// <returns></returns>
        public string ListAccount()
        {
            string MyReturn = string.Empty;

            // https://api.newsweaver.com/v2/

            return(MakeHttpWebRequest(BaseURL.ToString(), HttpVerb.GET));
        }
Ejemplo n.º 5
0
 public string Request(string method, string url, object o, NetworkCredential credential = null, WebHeaderCollection headers = null, bool useDefaultCredentials = false)
 {
     url = BaseURL.TrimEnd('/') + url;
     using (var resp = SendData(method, url, o, credential, headers, useDefaultCredentials))
     {
         return(ReadResponse(resp));
     }
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Takes an enum and returns the description of the enum
 /// </summary>
 /// <param name="value">BaseURL enum to get URL from</param>
 /// <returns>Description of the enum</returns>
 public static string ToDescriptionString(this BaseURL value)
 {
     return
         (value.GetType()
          .GetMember(value.ToString())
          .FirstOrDefault()
          ?.GetCustomAttribute <DescriptionAttribute>()
          ?.Description
          ?? value.ToString());
 }
Ejemplo n.º 7
0
        public async Task <IActionResult> GetMyCourse(int courseId, int userId)
        {
            var courses = await _repo.GetMyCourse(courseId, userId);



            if (courses.Image != null)
            {
                courses.Image = BaseURL.GetBaseUrl(Request) + "/Upload/" + courses.Image;
            }
            var courseToReturn = _mapper.Map <CourseForDetailedDto>(courses);



            return(Ok(courseToReturn));
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> GetCourseNew()
        {
            var courses = await _repo.GetCoursesNew();

            foreach (var course in courses)
            {
                if (course.Image != null)
                {
                    course.Image = BaseURL.GetBaseUrl(Request) + "/Upload/" + course.Image;
                }
            }

            var coursesToReturn = _mapper.Map <IEnumerable <CourseForListDto> >(courses);

            return(Ok(coursesToReturn));
        }
Ejemplo n.º 9
0
        public async Task <IActionResult> GetItem(int id)
        {
            var Items = await _repo.GetItem(id);

            if (Items.Files.TypeId == 1)
            {
                Items.Files.Url = BaseURL.GetBaseUrl(Request) + "/Upload/Video/" + Items.Files.Url;
            }
            if (Items.Files.TypeId == 2)
            {
                Items.Files.Url = BaseURL.GetBaseUrl(Request) + "/Upload/File/" + Items.Files.Url;
            }

            var ItemsToReturn = _mapper.Map <ItemForDetailedDto>(Items);

            return(Ok(ItemsToReturn));
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> GetFile(int id)
        {
            var item = await _repo.GetFile(id);

            if (item.TypeId == 1)
            {
                item.Url = BaseURL.GetBaseUrl(Request) + "/Upload/Video/" + item.Url;
            }
            if (item.TypeId == 2)
            {
                item.Url = BaseURL.GetBaseUrl(Request) + "/Upload/File/" + item.Url;
            }

            var photo = _mapper.Map <FileForDetailedDto>(item);

            return(Ok(photo));
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Not intended for batch retrievals, max 10 per minute
        /// </summary>
        /// <param name="mode"></param>
        /// <param name="beatmapId"></param>
        /// <param name="user"></param>
        /// <param name="type"></param>
        /// <param name="mods"></param>
        /// <returns>A byte array of the LZMA stream</returns>
        public static async Task <byte[]> GetReplay(Mode mode, int beatmapId, string user, UsernameType?type = null, Mods?mods = null)
        {
            QueueSize++;
            lock (LockReplay)
            {
                lock (Lock)
                {
                    if (RateLimitPerMin > 0)
                    {
                        int delay = (60000 + RateLimitPerMin - 1) / RateLimitPerMin;
                        Thread.Sleep(delay);
                    }
                }

                if (RateLimitPerMinReplay > 0)
                {
                    int delay = (60000 + RateLimitPerMinReplay - 1) / RateLimitPerMinReplay;
                    Thread.Sleep(delay);
                }
            }
            QueueSize--;

            var call = BaseURL
                       .AppendPathSegment("get_replay")
                       .SetQueryParam("k", Key)
                       .SetQueryParam("m", mode)
                       .SetQueryParam("b", beatmapId)
                       .SetQueryParam("u", user);

            if (type != null)
            {
                call.SetQueryParam("type", type);
            }
            if (mods != null)
            {
                call.SetQueryParam("mods", mods);
            }

            string json = await call
                          .GetAsync().ReceiveString();

            string content = JObject.Parse(json).Value <string>("content");

            return(Convert.FromBase64String(content));
        }
Ejemplo n.º 12
0
        private async Task <Uri> RenderUriAsync(string uri, object queryString = null, bool websocket = false)
        {
            if (queryString != null)
            {
                var keyValueContent       = ToKeyValue(queryString);
                var formUrlEncodedContent = new FormUrlEncodedContent(keyValueContent);
                var urlEncodedString      = await formUrlEncodedContent.ReadAsStringAsync();

                uri += "?" + urlEncodedString;
            }

            return(new Uri(
                       websocket
                ? new Uri(BaseURL.ToString()   // there's got to be a cleaner way to do this...
                          .Replace("http://", "ws://")
                          .Replace("https://", "wss://"))
                : BaseURL,
                       uri
                       ));
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> GetFiles()
        {
            var files = await _repo.GetFiles();

            foreach (var item in files)
            {
                if (item.TypeId == 1)
                {
                    item.Url = BaseURL.GetBaseUrl(Request) + "/Upload/Video/" + item.Url;
                }
                if (item.TypeId == 2)
                {
                    item.Url = BaseURL.GetBaseUrl(Request) + "/Upload/File/" + item.Url;
                }
            }


            var filesToReturn = _mapper.Map <IEnumerable <FileForListDto> >(files);

            return(Ok(filesToReturn));
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> GetItemOfLesson(int id)
        {
            var Items = await _repo.GetItemOfLesson(id);

            foreach (var item in Items)
            {
                if (item.Files.TypeId == 1)
                {
                    item.Files.Url = BaseURL.GetBaseUrl(Request) + "/Upload/Video/" + item.Files.Url;
                }
                if (item.Files.TypeId == 2)
                {
                    item.Files.Url = BaseURL.GetBaseUrl(Request) + "/Upload/File/" + item.Files.Url;
                }
            }

            var ItemsToReturn = _mapper.Map <IEnumerable <ItemForListDto> >(Items);


            return(Ok(ItemsToReturn));
        }
Ejemplo n.º 15
0
        public override void search(string vKeyword)
        {
            Console.WriteLine("Iniciando busca Valor Econômico");

            try
            {
                string vWord = BaseURL.Replace("KEYWORD", prepareKeyword(vKeyword));
                Document = Page.Load(vWord);
                Console.WriteLine("Selecionando resultados");
                var vLiNodes = Document.DocumentNode.SelectNodes("//li");
                if (vLiNodes != null)
                {
                    searchListResults(vLiNodes, vKeyword);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Erro -> {0}", e.Message);
                FLog.writeLog("Erro na palavra chave " + vKeyword + " no Valor econômico");
                FLog.writeLog("Descrição do erro: " + e.Message);
            }
        }
Ejemplo n.º 16
0
        public static async Task <MatchInfo> GetMatch(int matchId)
        {
            QueueSize++;
            lock (Lock)
            {
                if (RateLimitPerMin > 0)
                {
                    int delay = (60000 + RateLimitPerMin - 1) / RateLimitPerMin;
                    Thread.Sleep(delay);
                }
            }
            QueueSize--;

            var call = BaseURL
                       .AppendPathSegment("get_match")
                       .SetQueryParam("k", Key)
                       .SetQueryParam("mp", matchId);

            return(await call
                   .GetAsync()
                   .ReceiveJson <MatchInfo>());
        }
Ejemplo n.º 17
0
        public static async Task <List <User> > GetUser(string user, Mode?mode = null, UsernameType?type = null, int?eventDays = null)
        {
            QueueSize++;
            lock (Lock)
            {
                if (RateLimitPerMin > 0)
                {
                    int delay = (60000 + RateLimitPerMin - 1) / RateLimitPerMin;
                    Thread.Sleep(delay);
                }
            }
            QueueSize--;

            var call = BaseURL
                       .AppendPathSegment("get_user")
                       .SetQueryParam("k", Key);

            if (user != null)
            {
                call.SetQueryParam("u", user);
            }
            if (mode != null)
            {
                call.SetQueryParam("m", mode);
            }
            if (type != null)
            {
                call.SetQueryParam("type", type);
            }
            if (eventDays != null)
            {
                call.SetQueryParam("event_days ", eventDays);
            }

            return(await call
                   .GetAsync()
                   .ReceiveJson <List <User> >());
        }
Ejemplo n.º 18
0
        public async Task <IActionResult> GetLessonByCourse(int id)
        {
            var Lessons = await _repo.GetLessonByIdCourse(id);

            foreach (var lesson in Lessons)
            {
                foreach (var item in lesson.Items)
                {
                    if (item.Files.TypeId == 1)
                    {
                        item.Files.Url = BaseURL.GetBaseUrl(Request) + "/Upload/Video/" + item.Files.Url;
                    }
                    if (item.Files.TypeId == 2)
                    {
                        item.Files.Url = BaseURL.GetBaseUrl(Request) + "/Upload/File/" + item.Files.Url;
                    }
                }
            }

            var LessonsToReturn = _mapper.Map <IEnumerable <LessonForListDto> >(Lessons);

            return(Ok(LessonsToReturn));
        }
Ejemplo n.º 19
0
        public RestResponse <TOut> Send <TIn, TOut>(TIn message, string urlActionPart, Method method)
            where TIn : class
            where TOut : class
        {
            string toUrl = BaseURL;

            //join urlActionPart to BaseURL
            if (!string.IsNullOrEmpty(urlActionPart))
            {
                if (!BaseURL.EndsWith("/"))
                {
                    toUrl += "/" + urlActionPart;
                }
                else
                {
                    toUrl += urlActionPart;
                }
            }

            //add message to url
            if (method == Method.Get)
            {
                if (message != null)
                {
                    var sMessage  = Serialize(message);
                    var seperator = toUrl.Contains('?') ? "&" : "?";
                    toUrl += seperator + sMessage;
                }
            }

            var request = (HttpWebRequest)WebRequest.Create(toUrl);

            request.CookieContainer = cookieContainer;

            // add credentials
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                var credCache = new CredentialCache();

                credCache.Add(request.RequestUri, "Basic", new NetworkCredential(username, password));
                request.Credentials = credCache;
            }

            // add headers
            foreach (var header in headers)
            {
                request.Headers.Add(header.Key, header.Value);
            }


            if (method == Method.Get)
            {
                //save url for get
            }
            else
            {
                //set correct message for post
                switch (method)
                {
                case Method.Post:
                    request.Method = "POST";
                    break;

                case Method.Put:
                    request.Method = "PUT";
                    break;

                case Method.Patch:
                    request.Method = "PATCH";
                    break;

                case Method.Brew:
                    // http://www.ietf.org/rfc/rfc2324.txt
                    request.Method = "BREW";
                    break;
                }
                string sMessage;
                //if message is string, set content to form
                if (message is string)
                {
                    sMessage            = (string)(object)message;
                    request.ContentType = "application/x-www-form-urlencoded";
                }
                else
                {
                    //else set it to xml
                    sMessage            = Serialize(message);
                    request.ContentType = "text/xml";
                }

                using (var rStream = request.GetRequestStream())
                    using (var rwStream = new StreamWriter(rStream))
                    {
                        rwStream.Write(sMessage);
                        rwStream.Close();
                        rStream.Close();
                    }
            }

            request.Accept = "application/xml, */*";

            if (!string.IsNullOrEmpty(content_type))
            {
                request.ContentType = content_type;
            }

            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    //parse success-response
                    return(ParseResponse <TOut>(response));
                }
            }
            catch (WebException ex)
            {
                //try to parse error-response
                var response = ex.Response as HttpWebResponse;
                if (response != null)
                {
                    return(ParseResponse <TOut>(response));
                }
                throw;
            }
        }
Ejemplo n.º 20
0
        public string RenderPager()
        {
            var sb = new StringBuilder();

            PageMode = Mode.Links;

            if (!(string.IsNullOrEmpty(BaseURL)))
            {
                if (!(BaseURL.EndsWith("/")))
                {
                    BaseURL += "/";
                }
                if (!(BaseURL.StartsWith("/")))
                {
                    BaseURL = "/" + BaseURL;
                }
            }

            var qs = string.Empty;

            if (HttpContext.Current.Request.QueryString["ts"] != null)
            {
                qs = "?ts=" + HttpContext.Current.Request.QueryString["ts"];
            }

            if (PageCount > 1)
            {
                sb.Append("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"afpager\"><tr>");
                sb.Append("<td class=\"af_pager\">" + PageText + " " + CurrentPage + " " + OfText + " " + PageCount + "</td>");
                if (CurrentPage != 1)
                {
                    if (PageMode == Mode.Links)
                    {
                        if (string.IsNullOrEmpty(BaseURL))
                        {
                            sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"" + Utilities.NavigateUrl(TabID, "", BuildParams(View, ForumID, 1, TopicId)) + "\" title=\"First Page\"> &lt;&lt; </a></td>");
                            sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"" + Utilities.NavigateUrl(TabID, "", BuildParams(View, ForumID, CurrentPage - 1, TopicId)) + "\" title=\"Previous Page\"> &lt; </a></td>");
                        }
                        else
                        {
                            sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"" + BaseURL + qs + "\" title=\"First Page\"> &lt;&lt; </a></td>");
                            sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"" + BaseURL + (CurrentPage - 1) + "/" + qs + "\" title=\"Previous Page\"> &lt; </a></td>");
                        }
                    }
                    else
                    {
                        sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"javascript:" + string.Format(ClientScript, "1") + "\" title=\"First Page\"> &lt;&lt; </a></td>");
                        sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"javascript:" + string.Format(ClientScript, CurrentPage - 1) + "\" title=\"Previous Page\"> &lt; </a></td>");
                    }
                }

                int iStart;
                int iMaxPage;

                if (CurrentPage <= 3)
                {
                    iStart   = 1;
                    iMaxPage = 5;
                }
                else
                {
                    iStart   = CurrentPage - 2;
                    iMaxPage = CurrentPage + 2;
                }

                if (iMaxPage > PageCount)
                {
                    iMaxPage = PageCount;
                }

                if (iMaxPage == PageCount)
                {
                    iStart = iMaxPage - 4;
                }

                if (iStart <= 0)
                {
                    iStart = 1;
                }

                int i;
                for (i = iStart; i <= iMaxPage; i++)
                {
                    if (i == CurrentPage)
                    {
                        sb.Append("<td class=\"af_currentpage\" style=\"text-align:center;\">" + i + "</td>");
                    }
                    else
                    {
                        if (PageMode == Mode.Links)
                        {
                            if (string.IsNullOrEmpty(BaseURL))
                            {
                                sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"" + Utilities.NavigateUrl(TabID, "", BuildParams(View, ForumID, i, TopicId)) + "\">" + i + "</a></td>");
                            }
                            else
                            {
                                if (i > 1)
                                {
                                    sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"" + BaseURL + i + "/" + qs + "\">" + i + "</a></td>");
                                }
                                else
                                {
                                    sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"" + BaseURL + qs + "\">" + i + "</a></td>");
                                }
                            }
                        }
                        else
                        {
                            sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"javascript:" + string.Format(ClientScript, i) + "\">" + i + "</a></td>");
                        }
                    }

                    if (i == PageCount)
                    {
                        break;
                    }
                }

                if (CurrentPage != PageCount)
                {
                    if (PageMode == Mode.Links)
                    {
                        if (string.IsNullOrEmpty(BaseURL))
                        {
                            sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"" + Utilities.NavigateUrl(TabID, "", BuildParams(View, ForumID, CurrentPage + 1, TopicId)) + "\" title=\"Next Page\"> &gt;</a></td>");
                            sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"" + Utilities.NavigateUrl(TabID, "", BuildParams(View, ForumID, PageCount, TopicId)) + "\" title=\"Last Page\"> &gt;&gt;</a></td>");
                        }
                        else
                        {
                            sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"" + BaseURL + (CurrentPage + 1) + "/" + qs + "\" title=\"Next Page\"> &gt;</a></td>");
                            sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"" + BaseURL + PageCount + "/" + qs + "\" title=\"Last Page\"> &gt;&gt;</a></td>");
                        }
                    }
                    else
                    {
                        sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"javascript:" + string.Format(ClientScript, CurrentPage + 1) + "\" title=\"Next Page\"> &gt;</a></td>");
                        sb.Append("<td class=\"af_pagernumber\" style=\"text-align:center;\"><a href=\"javascript:" + string.Format(ClientScript, PageCount) + "\"> &gt;&gt;</a></td>");
                    }
                }

                sb.Append("</tr></table>");
            }

            return(sb.ToString());
        }
Ejemplo n.º 21
0
        /// <summary>
        /// List the Poppulo Accounts
        /// </summary>
        /// <param name="pageSize">Page Size</param>
        /// <returns></returns>
        public Task <List <XmlNode> > ListAccountsAsync(int?pageSize = null)
        {
            // Documentation: https://developer.poppulo.com/api-calls/api-list-accounts.html

            return(GetListEntitiesAsync(BaseURL.ToString(), PoppuloListType.Accounts, pageSize));
        }
Ejemplo n.º 22
0
        public async Task <IActionResult> AddAudio([FromForm] FileForAddDto fileForAddDto)
        {
            var file = fileForAddDto.File;

            fileForAddDto.TypeId = 1;
            var fileToCreate = _mapper.Map <File>(fileForAddDto);

            _repo.Add(fileToCreate);
            await _repo.SaveAll();

            if (file != null)
            {
                string newFileName = fileToCreate.Id + "_" + file.FileName;
                string path        = Path.Combine(_hostingEnv.ContentRootPath, "Upload/Audio", newFileName);
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    file.CopyTo(stream);
                    fileForAddDto.Url = newFileName;
                    fileToCreate.Url  = fileForAddDto.Url;
                    //_data.Entry(fileForAddDto).Property(x => x.Image).IsModified = true;
                    var fileFromRepo1 = await _repo.GetFile(fileToCreate.Id);

                    _mapper.Map(fileToCreate, fileFromRepo1);
                    await _repo.SaveAll();
                }
            }
            fileToCreate.Url = BaseURL.GetBaseUrl(Request) + "/Upload/Audio/" + fileForAddDto.Url;


            // var uploadResult = new VideoUploadResult();

            // if (file.Length > 0)
            // {
            //     using (var stream = file.OpenReadStream())
            //     {
            //         var uploadParams = new VideoUploadParams()
            //         {
            //             File = new FileDescription(file.Name, stream),

            //         };

            //         uploadResult = _cloudinary.Upload(uploadParams);
            //     }
            // }

            // fileForAddDto.Url = uploadResult.Uri.ToString();
            // fileForAddDto.PublicId = uploadResult.PublicId;
            // fileForAddDto.Duration = uploadResult.Duration;

            // fileForAddDto.ItemId = 1;
            // var data = _mapper.Map<File>(fileForAddDto);
            // _repo.Add(data);

            // if (await _repo.SaveAll())
            // {
            //     var photoToReturn = _mapper.Map<File>(data);
            //     return CreatedAtRoute("GetFile", new { id = data.Id }, photoToReturn);
            // }

            // return BadRequest("Could not add the photo");
            return(CreatedAtRoute("GetFile", new { id = fileToCreate.Id }, fileToCreate));
        }
Ejemplo n.º 23
0
        // await GetBeatmaps(since: null, beatmapsetId: null, beatmapId: null, user: null, type: null, mode: null, includeConverted: null, hash: null, limit: null, mods: null);
        public static async Task <List <Beatmap> > GetBeatmaps(DateTime?since = null, int?beatmapsetId = null, int?beatmapId = null, int?user = null, UsernameType?type = null, Mode?mode = null, bool?includeConverted = null, string hash = null, [Range(0, 500)] int?limit = null, Mods?mods = null)
        {
            QueueSize++;
            lock (Lock)
            {
                if (RateLimitPerMin > 0)
                {
                    int delay = (60000 + RateLimitPerMin - 1) / RateLimitPerMin;
                    Thread.Sleep(delay);
                }
            }
            QueueSize--;

            var call = BaseURL
                       .AppendPathSegment("get_beatmaps")
                       .SetQueryParam("k", Key);

            if (since != null)
            {
                call.SetQueryParam("since", since.ToString());
            }
            if (beatmapsetId != null)
            {
                call.SetQueryParam("s", beatmapsetId);
            }
            if (beatmapId != null)
            {
                call.SetQueryParam("b", beatmapId);
            }
            if (user != null)
            {
                call.SetQueryParam("u", user);
            }
            if (type != null)
            {
                call.SetQueryParam("type", type);
            }
            if (mode != null)
            {
                call.SetQueryParam("m", mode);
            }
            if (includeConverted != null)
            {
                call.SetQueryParam("a", includeConverted);
            }
            if (hash != null)
            {
                call.SetQueryParam("h", hash);
            }
            if (limit != null)
            {
                call.SetQueryParam("limit", limit);
            }
            if (mods != null)
            {
                call.SetQueryParam("mods", mods);
            }

            return(await call
                   .GetAsync()
                   .ReceiveJson <List <Beatmap> >());
        }
Ejemplo n.º 24
0
        public void Request(string url, HttpRequestInformation information, Stream responseStream)
        {
            if (url == null)
            {
                url = information == null ? string.Empty : information.Url;
            }
            StringBuilder stringBuilder = new StringBuilder();
            int           removeIndex   = -1;

            if (!url.StartsWith("http") && !string.IsNullOrEmpty(BaseURL))
            {
                stringBuilder.Append(BaseURL);
                if (!BaseURL.EndsWith("/"))
                {
                    stringBuilder.Append('/');
                }
                if (url.StartsWith("/"))
                {
                    removeIndex = stringBuilder.Length;
                }
            }
            stringBuilder.Append(url);
            if (removeIndex > -1)
            {
                stringBuilder.Remove(removeIndex, 1);
            }
            int  questionMarkIndex = url.IndexOf('?');
            bool hasParameter      = false;

            if (questionMarkIndex > -1)
            {
                if (questionMarkIndex == url.Length - 1)
                {
                    stringBuilder.Remove(questionMarkIndex, 1);
                }
                else
                {
                    hasParameter = true;
                }
            }
            if (information != null && information.QueryStringParameters != null && information.QueryStringParameters.Count > 0)
            {
                stringBuilder.Append(hasParameter ? '&' : '?');
                stringBuilder.Append(information.QueryStringParameters);
            }
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(stringBuilder.ToString());

            if (information != null)
            {
                if (information.FormData == null)
                {
                    httpWebRequest.Method = information.Type.ToString().ToUpperInvariant();
                }
                else
                {
                    httpWebRequest.Method = HttpRequestType.Post.ToString().ToUpperInvariant();
                }
            }
            httpWebRequest.CookieContainer = CookieContainer;
            if (OnRequest != null && !OnRequest(httpWebRequest))
            {
                return;
            }
            if (information != null && information.OnRequest != null && !information.OnRequest(httpWebRequest))
            {
                return;
            }
            byte[] buffer = new byte[BufferSize];
            if (information != null && information.FormData != null)
            {
                using (information.FormData) {
                    using (Stream stream = httpWebRequest.GetRequestStream()) {
                        while (true)
                        {
                            int length = information.FormData.Stream.Read(buffer, 0, buffer.Length);
                            if (information != null && information.OnRequesting != null && !information.OnRequesting(length))
                            {
                                break;
                            }
                            if (length < 1)
                            {
                                if (information != null && information.OnRequested != null)
                                {
                                    information.OnRequested();
                                }
                                break;
                            }
                            stream.Write(buffer, 0, length);
                        }
                    }
                }
            }
            HttpWebResponse httpWebResponse;

            try {
                httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            } catch (WebException webException) {
                httpWebResponse = webException.Response as HttpWebResponse;
                if (information == null || information.OnResponseError == null)
                {
                    if (httpWebResponse == null)
                    {
                        throw;
                    }
                }
                else
                {
                    if (OnResponseError != null && !OnResponseError(httpWebResponse, webException))
                    {
                        return;
                    }
                    if (information != null && information.OnResponseError != null && !information.OnResponseError(httpWebResponse, webException))
                    {
                        return;
                    }
                }
            }
            if (httpWebResponse == null)
            {
                return;
            }
            using (httpWebResponse) {
                if (OnResponse != null && !OnResponse(httpWebResponse))
                {
                    return;
                }
                if (information != null && information.OnResponse != null && !information.OnResponse(httpWebResponse))
                {
                    return;
                }
                using (Stream stream = httpWebResponse.GetResponseStream()) {
                    while (true)
                    {
                        int length = stream.Read(buffer, 0, buffer.Length);
                        if (information != null && information.OnResponding != null && !information.OnResponding(length))
                        {
                            break;
                        }
                        if (length == 0)
                        {
                            if (OnResponded != null)
                            {
                                OnResponded(responseStream);
                            }
                            responseStream.Position = 0;
                            if (information != null && information.OnResponded != null)
                            {
                                information.OnResponded(responseStream);
                            }
                            if (OnRespondedText != null || (information != null && information.OnRespondedText != null))
                            {
                                responseStream.Position = 0;
                                using (StreamReader streamReader = new StreamReader(responseStream, Encoding)) {
                                    string text = streamReader.ReadToEnd();
                                    if (OnRespondedText != null)
                                    {
                                        OnRespondedText(text);
                                    }
                                    if (information != null && information.OnRespondedText != null)
                                    {
                                        information.OnRespondedText(text);
                                    }
                                }
                            }
                            break;
                        }
                        responseStream.Write(buffer, 0, length);
                    }
                }
            }
        }