public async Task <IHttpActionResult> PostAsync(string parentId = null, string mail = null, bool extract = false, CancellationToken cancellationToken = default(CancellationToken))
        {
            int userId = ApiSecurity.CurrentUserId;
            var files  = new List <FileItem>();
            var parent = await FindFileAsync(parentId, cancellationToken);

            var parenti = parent == null ? default(int?) : parent.Id;
            var manager = new DriveManager(ApiSecurity.Manager, _services, ServerPaths.Map(ServerPaths.DriveFiles));

            using (var content = await Request.Content.ReadAsFileStreamAsync(cancellationToken))
            {
                files.Add(await manager.CreateFromStreamAsync(content.FileStream, parenti, userId, content.FileName, cancellationToken));
            }

            return(Ok(ListResult.Create(files.Select(file => new FileStoreUploadResult
            {
                Name = file.Name,
                Link = new Uri(Request.RequestUri, Url.Route(PublicRootName, new RouteValueDictionary
                {
                    { "userId", file.OwnerId },
                    { "path", file.PhysicalPath }
                }))
                       .AbsoluteUri
            }))));
        }
        /// <summary>
        /// Saves the media stream for the specified <paramref name="portal" />.
        /// </summary>
        /// <param name="portal">The portal which owns the media stream.</param>
        /// <param name="media">The media which contains information on the stream.</param>
        /// <param name="mediaStream">The media stream to save.</param>
        /// <param name="cancellationToken">A token to observe while waiting for the task to complete.</param>
        /// <returns>
        /// A task that represents the asynchronous operation.
        /// </returns>
        public virtual async Task SaveMediaStreamAsync(PortalItem portal, MediaItem media, Stream mediaStream, CancellationToken cancellationToken)
        {
            if (portal == null)
            {
                throw new ArgumentNullException(nameof(portal));
            }
            if (media == null)
            {
                throw new ArgumentNullException(nameof(media));
            }
            if (mediaStream == null)
            {
                throw new ArgumentNullException(nameof(mediaStream));
            }

            var directory = ServerPaths.Map(ServerPaths.PortalMedia, portal.Uri);

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            using (var fileStream = File.Create(Path.Combine(directory, media.Uri), 4096))
            {
                await mediaStream.CopyToAsync(fileStream);
            }
        }
 public async Task <IHttpActionResult> DeleteAllAsync([FromUri] IEnumerable <int> ids, CancellationToken cancellationToken)
 {
     if (ids != null)
     {
         await(new DriveManager(ApiSecurity.Manager, _services, ServerPaths.Map(ServerPaths.DriveFiles)).DeleteAsync(ids, cancellationToken));
     }
     return(StatusCode(HttpStatusCode.NoContent));
 }
 /// <summary>
 /// Gets the absolute URL for a media by its <paramref name="uri" />.
 /// </summary>
 /// <param name="portalUri">The portal URI.</param>
 /// <param name="mediaUri">The media URI.</param>
 /// <returns>
 /// The absolute URL for a media.
 /// </returns>
 public virtual string GetMediaLinkByUri(string portalUri, string mediaUri)
 {
     if (portalUri == null)
     {
         throw new ArgumentNullException(nameof(portalUri));
     }
     if (mediaUri == null)
     {
         throw new ArgumentNullException(nameof(mediaUri));
     }
     return(ServerPaths.Uri(ServerPaths.PortalMedia, portalUri, mediaUri).AbsoluteUri);
 }
        /// <summary>
        /// Reads the media stream for the specified <paramref name="portal" />.
        /// </summary>
        /// <param name="portal">The portal which owns the media stream.</param>
        /// <param name="media">The media which contains information on the stream.</param>
        /// <param name="cancellationToken">A token to observe while waiting for the task to complete.</param>
        /// <returns>
        /// A task that represents the asynchronous operation.
        /// </returns>
        public virtual Task <Stream> ReadMediaStreamAsync(PortalItem portal, MediaItem media, CancellationToken cancellationToken)
        {
            if (portal == null)
            {
                throw new ArgumentNullException(nameof(portal));
            }
            if (media == null)
            {
                throw new ArgumentNullException(nameof(media));
            }

            var directory = ServerPaths.Map(ServerPaths.PortalMedia, portal.Uri, media.Uri);

            return(Task.FromResult <Stream>(File.OpenRead(Path.Combine(directory, media.Name))));
        }
        public async Task <IHttpActionResult> PostAsync([FromBody] FileItem model, CancellationToken cancellationToken)
        {
            ModelState.Remove("model.Slug");
            if (model == null || !ModelState.IsValid)
            {
                return(BadRequest());
            }

            var manager = new DriveManager(ApiSecurity.Manager, _services, ServerPaths.Map(ServerPaths.DriveFiles));

            model = await manager.CreateAsync(model, ApiSecurity.CurrentUserId, cancellationToken);

            return(CreatedAtRoute(GetByIdRouteName, new RouteValueDictionary {
                { "id", model.Id }
            }, model));
        }
Esempio n. 7
0
        public ConfigService(IConfiguration config)
        {
            _config = config;
            _paths  = new ServerPaths();
            _config.GetSection(LocationSection).Bind(_paths);

            ServerLocation       = checkExistance(_paths.Server) as DirectoryInfo;
            LogLocation          = checkExistance(_paths.Logs) as DirectoryInfo;
            PythonLocation       = checkExistance(_paths.Python) as FileInfo;
            NbtConverterLocation = checkExistance(_paths.NbtConverter) as FileInfo;
            OverviewerLocation   = checkExistance(_paths.Overviewer) as FileInfo;

            TempLocation = ensureExistance(_paths.Temp);
            DataLocation = ensureExistance(_paths.Data);

            Uri.TryCreate(_paths.OverviewerUrl, UriKind.Absolute, out var url);
            OverviewerUrl = url;

            InitialRunIndex = ensureInt(InitialRunIndexKey);
        }
        /// <summary>
        /// Deletes a media <see cref="Stream" /> from the specified <paramref name="portal" /> as an asynchronous operation.
        /// </summary>
        /// <param name="portal">The portal which owns the media stream.</param>
        /// <param name="media">The media which contains information on the stream.</param>
        /// <param name="cancellationToken">A token to observe while waiting for the task to complete.</param>
        /// <returns>
        /// A task that represents the asynchronous operation.
        /// </returns>
        public virtual Task DeleteMediaStreamAsync(PortalItem portal, MediaItem media, CancellationToken cancellationToken)
        {
            if (portal == null)
            {
                throw new ArgumentNullException(nameof(portal));
            }
            if (media == null)
            {
                throw new ArgumentNullException(nameof(media));
            }

            var fileName = ServerPaths.Map(ServerPaths.PortalMedia, portal.Uri, media.Uri);

            if (File.Exists(fileName))
            {
                File.Delete(fileName);
            }

            return(Task.CompletedTask);
        }
Esempio n. 9
0
        public async Task <object> Call(AsyncServiceMethodInfo asyncServiceMethodInfo, CallParam[] callParams)
        {
            try
            {
                // Get the URI for the HTTP server call.
                ServerPath path = ServerPaths.GetServerPath(asyncServiceMethodInfo);

                using (var httpClient = new HttpClient())
                {
                    using (HttpContent content = HttpContentSupport.Create(callParams))
                    {
                        HttpResponseMessage response = await httpClient.PostAsync(_rootUri + path, content).ConfigureAwait(false);

                        if (!response.IsSuccessStatusCode)
                        {
                            throw new ServerCallException(asyncServiceMethodInfo, response.StatusCode);
                        }

                        using (Stream responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                        {
                            if (responseStream == null)
                            {
                                throw new ServerCallException(asyncServiceMethodInfo, HttpStatusCode.NoContent);
                            }

                            using (var reader = new StreamReader(responseStream, Encoding.UTF8))
                            {
                                string responseJson = await reader.ReadToEndAsync().ConfigureAwait(false);

                                return(JsonConvert.DeserializeObject(responseJson, asyncServiceMethodInfo.ReturnType));
                            }
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                throw new ServerCallException(asyncServiceMethodInfo, "Exception during server method call", exception);
            }
        }
        public async Task <WebQueryResult> ProcessRequest(string query, CallbackTypeEnum type, string ip, WebAuthUserData data)
        {
            if (!Settings.Config.ModuleContractNotifications)
            {
                return(WebQueryResult.False);
            }

            try
            {
                RunningRequestCount++;
                if (!query.Contains("&state=12"))
                {
                    return(WebQueryResult.False);
                }

                var prms = query.TrimStart('?').Split('&');
                var code = prms[0].Split('=')[1];

                var result = await WebAuthModule.GetCharacterIdFromCode(code,
                                                                        Settings.WebServerModule.CcpAppClientId, Settings.WebServerModule.CcpAppSecret);

                if (result == null)
                {
                    return(WebQueryResult.EsiFailure);
                }

                var characterId   = result[0];
                var numericCharId = Convert.ToInt64(characterId);

                if (string.IsNullOrEmpty(characterId))
                {
                    await LogHelper.LogWarning("Bad or outdated feed request!");

                    var r = WebQueryResult.BadRequestToSystemAuth;
                    r.Message1 = LM.Get("accessDenied");
                    return(r);
                }

                if (!HasAuthAccess(numericCharId))
                {
                    await LogHelper.LogWarning($"Unauthorized feed request from {characterId}");

                    var r = WebQueryResult.BadRequestToSystemAuth;
                    r.Message1 = LM.Get("accessDenied");
                    return(r);
                }

                if (WebGetAuthGroup(numericCharId, out _) == null)
                {
                    await LogHelper.LogWarning("Feed auth group not found!");

                    var r = WebQueryResult.BadRequestToSystemAuth;
                    r.Message1 = LM.Get("accessDenied");
                    return(r);
                }

                //var rChar = await APIHelper.ESIAPI.GetCharacterData(Reason, characterId, true);

                await SQLHelper.InsertOrUpdateTokens("", characterId, "", result[1]);

                await LogHelper.LogInfo($"Mail feed added for character: {characterId}", LogCat.AuthWeb);

                var res = WebQueryResult.ContractsAuthSuccess;
                res.Message1 = LM.Get("mailAuthSuccessHeader");
                res.Message2 = LM.Get("mailAuthSuccessBody");
                res.AddValue("url", ServerPaths.GetFeedSuccessUrl());
                return(res);
            }
            catch (Exception ex)
            {
                await LogHelper.LogEx(ex.Message, ex, Category);
            }
            finally
            {
                RunningRequestCount--;
            }

            return(WebQueryResult.False);
        }
        protected virtual bool TryExecuteOnServer(
            string pathToTool,
            string responseFileCommands,
            string commandLineCommands,
            out int result)
        {
#if !NETFRAMEWORK
            if (!SuppressCurrentUserOnlyPipeOptions && !Enum.IsDefined(typeof(PipeOptions), PipeOptionCurrentUserOnly))
            {
                // For security reasons, we don't want to spin up a server that doesn't
                // restrict requests only to the current user.
                result = -1;

                return(ForceServer);
            }
#endif

            Log.LogMessage(StandardOutputLoggingImportance, "Server execution started.");
            using (_razorServerCts = new CancellationTokenSource())
            {
                Log.LogMessage(StandardOutputLoggingImportance, $"CommandLine = '{commandLineCommands}'");
                Log.LogMessage(StandardOutputLoggingImportance, $"ServerResponseFile = '{responseFileCommands}'");

                // The server contains the tools for discovering tag helpers and generating Razor code.
                var clientDir   = Path.GetFullPath(Path.GetDirectoryName(ToolAssembly));
                var workingDir  = CurrentDirectoryToUse();
                var tempDir     = ServerConnection.GetTempPath(workingDir);
                var serverPaths = new ServerPaths(
                    clientDir,
                    workingDir: workingDir,
                    tempDir: tempDir);

                var arguments = GetArguments(responseFileCommands);

                var responseTask = ServerConnection.RunOnServer(PipeName, arguments, serverPaths, _razorServerCts.Token, debug: DebugTool);
                responseTask.Wait(_razorServerCts.Token);

                var response = responseTask.Result;
                if (response.Type == ServerResponse.ResponseType.Completed &&
                    response is CompletedServerResponse completedResponse)
                {
                    result = completedResponse.ReturnCode;

                    if (result == 0)
                    {
                        // Server execution succeeded.
                        Log.LogMessage(StandardOutputLoggingImportance, $"Server execution completed with return code {result}.");

                        // There might still be warnings in the error output.
                        if (LogStandardErrorAsError)
                        {
                            LogErrors(completedResponse.ErrorOutput);
                        }
                        else
                        {
                            LogMessages(completedResponse.ErrorOutput, StandardErrorLoggingImportance);
                        }

                        return(true);
                    }
                    else if (result == 2)
                    {
                        // Server execution completed with a legit error. No need to fallback to cli execution.
                        Log.LogMessage(StandardOutputLoggingImportance, $"Server execution completed with return code {result}. For more info, check the server log file in the location specified by the RAZORBUILDSERVER_LOG environment variable.");

                        if (LogStandardErrorAsError)
                        {
                            LogErrors(completedResponse.ErrorOutput);
                        }
                        else
                        {
                            LogMessages(completedResponse.ErrorOutput, StandardErrorLoggingImportance);
                        }

                        return(true);
                    }
                    else
                    {
                        // Server execution completed with an error but we still want to fallback to cli execution.
                        Log.LogMessage(StandardOutputLoggingImportance, $"Server execution completed with return code {result}. For more info, check the server log file in the location specified by the RAZORBUILDSERVER_LOG environment variable.");
                    }
                }
                else
                {
                    // Server execution failed. Fallback to cli execution.
                    Log.LogMessage(
                        StandardOutputLoggingImportance,
                        $"Server execution failed with response {response.Type}. For more info, check the server log file in the location specified by the RAZORBUILDSERVER_LOG environment variable.");

                    result = -1;
                }

                if (ForceServer)
                {
                    // We don't want to fallback to in-process execution.
                    return(true);
                }

                Log.LogMessage(StandardOutputLoggingImportance, "Fallback to in-process execution.");
            }

            return(false);
        }
Esempio n. 12
0
        protected virtual bool TryExecuteOnServer(
            string pathToTool,
            string responseFileCommands,
            string commandLineCommands,
            out int result)
        {
            Log.LogMessage(StandardOutputLoggingImportance, "Server execution started.");
            using (_razorServerCts = new CancellationTokenSource())
            {
                Log.LogMessage(StandardOutputLoggingImportance, $"CommandLine = '{commandLineCommands}'");
                Log.LogMessage(StandardOutputLoggingImportance, $"ServerResponseFile = '{responseFileCommands}'");

                // The server contains the tools for discovering tag helpers and generating Razor code.
                var clientDir   = Path.GetDirectoryName(ToolAssembly);
                var workingDir  = CurrentDirectoryToUse();
                var tempDir     = ServerConnection.GetTempPath(workingDir);
                var serverPaths = new ServerPaths(
                    clientDir,
                    workingDir: workingDir,
                    tempDir: tempDir);

                var arguments = GetArguments(responseFileCommands);

                var responseTask = ServerConnection.RunOnServer(PipeName, arguments, serverPaths, _razorServerCts.Token, debug: DebugTool);
                responseTask.Wait(_razorServerCts.Token);

                var response = responseTask.Result;
                if (response.Type == ServerResponse.ResponseType.Completed &&
                    response is CompletedServerResponse completedResponse)
                {
                    result = completedResponse.ReturnCode;

                    if (result == 0)
                    {
                        Log.LogMessage(StandardOutputLoggingImportance, $"Server execution completed with return code {result}.");
                        return(true);
                    }
                    else
                    {
                        Log.LogMessage(StandardOutputLoggingImportance, $"Server execution completed with return code {result}. For more info, check the server log file in the location specified by the RAZORBUILDSERVER_LOG environment variable.");

                        if (LogStandardErrorAsError)
                        {
                            LogErrors(completedResponse.ErrorOutput);
                        }
                        else
                        {
                            LogMessages(completedResponse.ErrorOutput, StandardErrorLoggingImportance);
                        }

                        return(true);
                    }
                }
                else
                {
                    Log.LogMessage(
                        StandardOutputLoggingImportance,
                        $"Server execution failed with response {response.Type}. For more info, check the server log file in the location specified by the RAZORBUILDSERVER_LOG environment variable.");

                    result = -1;
                }

                if (ForceServer)
                {
                    // We don't want to fallback to in-process execution.
                    return(true);
                }

                Log.LogMessage(StandardOutputLoggingImportance, "Fallback to in-process execution.");
            }

            return(false);
        }
Esempio n. 13
0
        public async Task <WebQueryResult> ProcessRequest(string query, CallbackTypeEnum type, string ip, WebAuthUserData data)
        {
            if (!Settings.Config.ModuleNotificationFeed)
            {
                return(WebQueryResult.False);
            }

            try
            {
                RunningRequestCount++;
                if (query.Contains("&state=9"))
                {
                    //var prms = QueryHelpers.ParseQuery(query);
                    var prms = query.TrimStart('?').Split('&');
                    var code = prms[0].Split('=')[1];

                    var result = await WebAuthModule.GetCharacterIdFromCode(code,
                                                                            Settings.WebServerModule.CcpAppClientId, Settings.WebServerModule.CcpAppSecret);

                    if (result == null)
                    {
                        return(WebQueryResult.EsiFailure);
                    }

                    var characterId   = result[0];
                    var numericCharId = Convert.ToInt64(characterId);

                    if (string.IsNullOrEmpty(characterId))
                    {
                        await LogHelper.LogWarning("Bad or outdated notify feed request!");

                        var r = WebQueryResult.BadRequestToSystemAuth;
                        r.Message1 = LM.Get("authTokenBodyFail");
                        r.Message2 = LM.Get("authTokenBadRequest");
                        return(r);
                    }

                    if (!TickManager.GetModule <NotificationModule>().IsValidCharacter(numericCharId))
                    {
                        await LogHelper.LogWarning($"Unauthorized notify feed request from {characterId}");

                        var r = WebQueryResult.BadRequestToSystemAuth;
                        r.Message1 = LM.Get("authTokenBodyFail");
                        return(r);
                    }

                    var rChar = await APIHelper.ESIAPI.GetCharacterData(Reason, characterId, true);

                    await SQLHelper.InsertOrUpdateTokens(result[1] ?? "", characterId, null, null);

                    await LogHelper.LogInfo($"Notification feed added for character: {characterId}", LogCat.AuthWeb);

                    var res = WebQueryResult.GeneralAuthSuccess;
                    res.Message1 = LM.Get("authTokenRcv");
                    res.Message2 = LM.Get("authTokenRcv2", rChar.name);
                    res.AddUrl(ServerPaths.GetFeedSuccessUrl());
                    return(res);
                }
            }
            catch (Exception ex)
            {
                await LogHelper.LogEx(ex.Message, ex, Category);
            }
            finally
            {
                RunningRequestCount--;
            }

            return(WebQueryResult.False);
        }
 public async Task <IHttpActionResult> DeleteAsync(int id, CancellationToken cancellationToken)
 {
     //SecurityHelper.Authorize(Services.User, AccessSource.File, id, AccessPermission.IsOwner);
     await(new DriveManager(ApiSecurity.Manager, _services, ServerPaths.Map(ServerPaths.DriveFiles)).DeleteAsync(id, cancellationToken));
     return(StatusCode(HttpStatusCode.NoContent));
 }