示例#1
0
        public static object Run(
            HttpContext context
            , string configuration
            , IList <object> dataservices
            )
        {
            // Retrieve DataService
            if (dataservices == null || dataservices.Count == 0)
            {
                return new { error = "Data Services not provided" }
            }
            ;
            SQL db = (SQL)dataservices.FirstOrDefault();

            if (db == null)
            {
                return new { error = "Data Service not provided" }
            }
            ;

            // Query
            var query = WebTools.Get(context, "query");

            if (string.IsNullOrEmpty(query) == false)
            {
                var result = db.Query(query);

                // Return Result
                return(JsonConvert.SerializeObject(result));
            }

            return(new { error = "query not specified" });
        }
    }
}
示例#2
0
        // Given id and password, authenticate the user
        public static bool Authenticate(HttpContext context)
        {
            bool authenticated = false;

            // get user id and password
            string id            = WebTools.Get(context, "id");
            string password      = WebTools.Get(context, "password");
            string navigation_id = WebTools.GetNavigationId(context);

            if (string.IsNullOrEmpty(id) == false && string.IsNullOrEmpty(navigation_id) == false)
            {
                // find user with matching id and password
                var db    = (SQL)context.Items["db"];
                var param = new Dictionary <string, object>();
                param["id"] = id; param["navigation_id"] = navigation_id;
                var users = db.Query(
                    "SELECT * FROM core_user WHERE id = @id AND navigation_id = @navigation_id"
                    , param);

                if (users != null && users.Count() == 1)
                {
                    var user = users.First();

                    bool valid = false;
                    // if password is DBNull and also empty then pass
                    if (user.Get("password") is DBNull || string.IsNullOrEmpty($"{user.Get("password")}"))
                    {
                        valid = true;
                    }

                    // Verify the password
                    else if (SecurePasswordHasher.Verify(password, $"{user.Get("password")}"))
                    {
                        valid = true;
                    }

                    if (valid)
                    {
                        // create a new token
                        var token = JwtTool.CreateToken(
                            context
                            , $"{user["id"]}"
                            , $"{user["name"]}"
                            , RolesOfUser(context, $"{user["_id"]}")
                            );

                        RefreshHeader(context, token);
                        // is authenticated
                        authenticated = true;
                    }
                }
            }

            return(authenticated);
        }
        private void treeResults_KeyDown(object sender, KeyEventArgs e)
        {
            TreeView tv = (TreeView)sender;

            if (e.Shift)
            {
                this.displayShowSettings(tv);
            }
            else if (e.Alt)
            {
                StringCollection IMDB_IDs = this.userSettingsTool.SHOW_DATA;
                Show             show     = this.findShow(tv);
                var tvShowStoredString    = this.userSettingsTool.GetTVShowStoredStringByTitle(show.Title);

                if (tvShowStoredString.IMDB_ID != null)
                {
                    string searchString = "";
                    if (this.isNode(tv))
                    {
                        Regex pattern = new Regex(@"S\d+E\d+");
                        Match match   = pattern.Match(tv.SelectedNode.Text);
                        searchString = tvShowStoredString.IMDB_ID + " " + match.Value;
                    }
                    else
                    {
                        searchString = tvShowStoredString.IMDB_ID;
                    }

                    WebTools.Get().OpenUrl(String.Format(RARBG_URL, searchString).Replace(" ", "%20"));
                }
                else
                {
                    MessageBox.Show(
                        "No IMDB ID for this Show, try adding it by pushing CTRL while the show is selected.",
                        "Error",
                        MessageBoxButtons.OK,
                        MessageBoxIcon.Error
                        );
                }
            }
            else if (e.KeyCode == Keys.D)
            {
                this.removeTreeNode(tv);
            }
            else if (e.Control && e.KeyCode == Keys.C)
            {
                Clipboard.SetText(tv.SelectedNode.Name);
            }
        }
示例#4
0
        public static object Run(
            HttpContext context
            , string configuration
            , IList <object> dataservices
            )
        {
            // Get Configuration
            if (string.IsNullOrEmpty(configuration))
            {
                return new { error = "No configuration specified." }
            }
            ;
            JObject config = JsonConvert.DeserializeObject <JObject>(configuration);

            // check parameters
            string folder = $"{config["folder"]}";

            if (string.IsNullOrEmpty(folder) == true)
            {
                return new { error = "No folder specified." }
            }
            ;

            // Get filepath
            string filepath = Path.Combine(folder, WebTools.Get(context, "filepath"));

            if (string.IsNullOrEmpty(filepath) == true)
            {
                return new { error = "No filepath specified" }
            }
            ;

            // Get File
            context.Response.Headers["Content-Disposition"] = $"inline;FileName={Path.GetFileName(filepath)}";

            using (MemoryStream ms = new MemoryStream())
                using (FileStream file = new FileStream(filepath, FileMode.Open, FileAccess.Read))
                {
                    byte[] bytes = new byte[file.Length];
                    file.Read(bytes, 0, (int)file.Length);
                    ms.Write(bytes, 0, (int)file.Length);

                    return(ms.ToArray());
                }
        }
    }
}
示例#5
0
 private void linkTorrentFreak_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     WebTools.Get().OpenUrl("https://torrentfreak.com");
 }
示例#6
0
        public static object Run(
            HttpContext context
            , string configuration
            , IList <object> dataservices
            )
        {
            // Get Configuration
            if (string.IsNullOrEmpty(configuration))
            {
                return new { error = "No configuration specified." }
            }
            ;
            JObject config = JsonConvert.DeserializeObject <JObject>(configuration);

            // check parameters
            string table = $"{config["table"]}"; if (string.IsNullOrEmpty(table) == true)

            {
                return new { error = "No table specified." }
            }
            ;
            string filepathCol = $"{config["filepath"]}"; if (string.IsNullOrEmpty(filepathCol) == true)

            {
                return new { error = "No filepath configured." }
            }
            ;
            string contentCol = $"{config["content"]}"; if (string.IsNullOrEmpty(contentCol) == true)

            {
                return new { error = "No content specified." }
            }
            ;

            // Get Navigation ID
            string navigation_id = WebTools.GetNavigationId(context);

            if (string.IsNullOrEmpty(navigation_id))
            {
                return new { error = "No X-App-Key specified" }
            }
            ;

            // Retrieve DataService
            if (dataservices == null || dataservices.Count == 0)
            {
                return new { error = "Data Services not provided" }
            }
            ;
            SQL db = (SQL)dataservices.FirstOrDefault();

            if (db == null)
            {
                return new { error = "Data Service not provided" }
            }
            ;

            // Get filepath
            string filepath = WebTools.Get(context, "filepath");

            if (string.IsNullOrEmpty(filepath) == true)
            {
                return new { error = "No filepath specified" }
            }
            ;

            // Get File
            context.Response.Headers["Content-Disposition"] = $"inline;FileName={Path.GetFileName(filepath)}";

            // Read file from the SQL table
            using (MemoryStream ms = new MemoryStream())
            {
                var parameters = new Dictionary <string, object>();

                parameters[filepathCol] = filepath;

                var result = db.Query($@"SELECT {contentCol} FROM {table} WHERE {filepathCol}=@{filepathCol}", parameters);
                if (result != null && result.Count() > 0)
                {
                    return(result[0][contentCol]);
                }
            }

            return(null);
        }
    }
}
示例#7
0
        public async Task <string> Process(HttpContext context)
        {
            string result = null;

            // get relative path
            var    navigation     = (IDictionary <string, object>)context.Items["navigation"];
            string navigationPath = navigation.Get("url")?.ToString();

            // db
            var db = (SQL)context.Items["db"];

            var regex = new Regex(Regex.Escape(navigationPath));

            string[] relativePaths = regex
                                     .Replace(context.Request.Path.ToString(), "", 1)
                                     .Split("/");

            // get websvc name
            string websvcName = string.Empty;

            if (relativePaths.Length > 1)
            {
                websvcName = relativePaths[1];
            }

            // get navigation id
            string navigationId = navigation.Get("_id")?.ToString();

            // load web services
            if (
                string.IsNullOrEmpty(websvcName) == false &&
                string.IsNullOrEmpty(navigationId) == false
                )
            {
                var serviceParam = new Dictionary <string, object>();
                serviceParam["navigation_id"] = navigationId;
                serviceParam["api_url"]       = websvcName;
                var service = db.Query(
                    @"SELECT * FROM core_websvc WHERE navigation_id=@navigation_id AND api_url=@api_url"
                    , serviceParam
                    ).First();

                // services exists and provides api for the method
                string method = context.Request.Method.ToLower();
                if (service != null)
                {
                    // load workflow
                    string workflow_id = service.Get($"{method}_workflow")?.ToString();
                    if (string.IsNullOrEmpty(workflow_id) == false)
                    {
                        var workflowParam = new Dictionary <string, object>();
                        workflowParam["_id"] = workflow_id;
                        var workflow = db.Query(
                            @"SELECT * FROM core_workflow WHERE _id=@_id"
                            , workflowParam
                            ).First();
                        if (workflow != null)
                        {
                            // Prepare inputs to the script
                            IDictionary <string, object> Inputs = new Dictionary <string, object>();

                            // load datasources
                            var dataservices = new List <object>();
                            var dsIds        = service.GetArray($"{method}_datasource") as object[];
                            foreach (object dsId in dsIds)
                            {
                                if (string.IsNullOrEmpty($"{dsId}") == false)
                                {
                                    // load datasource
                                    var dataserviceParam = new Dictionary <string, object>();
                                    dataserviceParam["_id"] = dsId;
                                    var dataservice = db.Query(
                                        "SELECT * FROM core_dataservice WHERE _id=@_id"
                                        , dataserviceParam).First();

                                    var createdDS = new SQL($"{dataservice.Get("connectionString")}");

                                    // instantiate
                                    dataservices.Add(createdDS);
                                }
                            }

                            // produce entire script
                            object scriptResult = await Script.Run(
                                context
                                , $"{workflow?.Get("_id")}"
                                , $"{service.Get($"{method}_configuration")}"
                                , dataservices);

                            // if script result is string
                            if (scriptResult != null && scriptResult.GetType() == typeof(string))
                            {
                                result = scriptResult.ToString();
                                // jsonp
                                string callback = WebTools.Get(context, "callback");
                                if (string.IsNullOrEmpty(callback) == false)
                                {
                                    result = $"{callback}({result})";
                                }
                            }

                            // if script result is anonymous type
                            else if (scriptResult != null && scriptResult.GetType().Name.Contains("AnonymousType"))
                            {
                                // return json serialized format
                                result = JsonConvert.SerializeObject(scriptResult);
                            }

                            // if script result is not string
                            else if (scriptResult != null)
                            {
                                // response with token
                                byte[] byteResult = (byte[])scriptResult;
                                await context.Response.Body.WriteAsync(byteResult, 0, byteResult.Length);
                            }
                        }
                    }
                }
            }

            return(result);
        }
示例#8
0
        public static object Run(
            HttpContext context
            , string configuration
            , IList <object> dataservices
            )
        {
            // Get Configuration
            if (string.IsNullOrEmpty(configuration))
            {
                return new { error = "No configuration specified." }
            }
            ;
            JObject config = JsonConvert.DeserializeObject <JObject>(configuration);

            // Calculate Pagination
            string page = WebTools.Get(context, "page"); if (string.IsNullOrEmpty(page))
            {
                page = "1";
            }
            string size = WebTools.Get(context, "size"); if (string.IsNullOrEmpty(size))
            {
                size = "10";
            }

            // Query Options - Sort
            var sort = new List <string>();

            if (WebTools.GetArray(context, "_sort")?.Count() > 0)
            {
                foreach (var sortKey in WebTools.GetArray(context, "_sort"))
                {
                    sort.Add($"{sortKey}");
                }
            }

            if (WebTools.GetArray(context, "_sort_desc")?.Count() > 0)
            {
                foreach (var sortKey in WebTools.GetArray(context, "_sort_desc"))
                {
                    sort.Add($"{sortKey} DESC");
                }
            }

            // Query - Filters
            var where = new List <string>();
            var parameters = new Dictionary <string, object>();

            // get body
            var data = JsonConvert.DeserializeObject <JObject>(WebTools.GetBody(context));

            if (data == null)
            {
                data = new JObject();
            }

            // append querystring to the data
            foreach (var key in context.Request.Query.Keys)
            {
                data[key] = new JArray(context.Request.Query[key].ToArray());
            }

            string[] searchFields = config["searchFields"]?.ToObject <string[]>();
            if (data != null && data.Count > 0)
            {
                foreach (var item in data)
                {
                    string parameterName = item.Key
                                           .Replace(".", "_")
                                           .Replace("_lte", "")
                                           .Replace("_gte", "")
                                           .Replace("_lt", "")
                                           .Replace("_gt", "")
                    ;

                    if (item.Key == "page")
                    {
                        continue;
                    }
                    else if (item.Key == "size")
                    {
                        continue;
                    }
                    else if (item.Key == "_export")
                    {
                        continue;
                    }
                    else if (item.Key == "_aggregation")
                    {
                        continue;
                    }
                    else if (item.Key == "_sort")
                    {
                        continue;
                    }
                    else if (item.Key == "_sort_desc")
                    {
                        continue;
                    }

                    // search keyword
                    else if (item.Key == "_search" && searchFields != null)
                    {
                        if (string.IsNullOrEmpty($"{item.Value.FirstOrDefault()}") == false)
                        {
                            IList <string> search = new List <string>();
                            foreach (var searchKey in searchFields)
                            {
                                search.Add($"{searchKey} LIKE '%'+@{parameterName}+'%'");
                            }
                            where.Add($"({string.Join(" OR ", search)})");

                            parameters[parameterName] = $"{item.Value.FirstOrDefault()}";
                        }
                        continue;
                    }

                    // range filter
                    else if (item.Key.EndsWith("_date_gte"))
                    {
                        where.Add($"{item.Key.Replace("_gte", "")} >= @{parameterName}");
                    }

                    else if (item.Key.EndsWith("_date_lte"))
                    {
                        where.Add($"{item.Key.Replace("_lte", "")} <= @{parameterName}");
                    }

                    else if (item.Key.EndsWith("_date_gt"))
                    {
                        where.Add($"{item.Key.Replace("_gt", "")} > @{parameterName}");
                    }

                    else if (item.Key.EndsWith("_date_lt"))
                    {
                        where.Add($"{item.Key.Replace("_lt", "")} < @{parameterName}");
                    }

                    // otherwise string filter
                    else
                    {
                        foreach (var str in item.Value)
                        {
                            where.Add($"{item.Key} = @{parameterName}");
                        }
                    }

                    // add to parameters
                    parameters[parameterName] = $"{item.Value.FirstOrDefault()}";
                }
            }

            // check if any filter options exists
            JArray defaultFilters = (JArray)config["defaultFilters"];

            if (defaultFilters != null)
            {
                foreach (var filter in defaultFilters)
                {
                    string filterType = $"{filter["type"]}";
                    switch (filterType)
                    {
                    case "headers":
                        string key    = $"{filter["key"]}";
                        string column = $"{filter["column"]}";

                        if (context.Request.Headers.ContainsKey(key))
                        {
                            where.Add($"{column} = @{column}");
                            parameters[column] = $"{context.Request.Headers[key]}";
                        }
                        break;
                    }
                }
            }

            // Retrieve DataService
            if (dataservices == null || dataservices.Count == 0)
            {
                return new { error = "Data Services not provided" }
            }
            ;
            SQL db = (SQL)dataservices.FirstOrDefault();

            if (db == null)
            {
                return new { error = "Data Service not provided" }
            }
            ;

            // get sql list parameters
            string sqlTemplate = $"{config["sql"]}";

            if (string.IsNullOrEmpty(sqlTemplate))
            {
                return new { error = "No sql template specified." }
            }
            ;

            var result = List(
                db
                , sqlTemplate
                , config
                , where
                , parameters
                , sort
                , Int64.Parse(size)
                , Int64.Parse(page));

            var total = Count(db, sqlTemplate, where, parameters);

            // Return Result
            var pagedResult = new
            {
                page,
                size,
                total,
                data = result
            };

            return(JsonConvert.SerializeObject(
                       pagedResult,
                       new JsonSerializerSettings {
                Formatting = Formatting.Indented
            }
                       ));
        }
示例#9
0
        public static object Run(
            HttpContext context
            , string configuration
            , IList <object> dataservices
            )
        {
            // Get Configuration
            if (string.IsNullOrEmpty(configuration))
            {
                return new { error = "No configuration specified." }
            }
            ;
            JObject config = JsonConvert.DeserializeObject <JObject>(configuration);

            // check parameters
            string table = $"{config["table"]}"; if (string.IsNullOrEmpty(table) == true)

            {
                return new { error = "No table specified." }
            }
            ;
            string filepathCol = $"{config["filepath"]}"; if (string.IsNullOrEmpty(filepathCol) == true)

            {
                return new { error = "No filepath configured." }
            }
            ;
            string contentCol = $"{config["content"]}"; if (string.IsNullOrEmpty(contentCol) == true)

            {
                return new { error = "No content specified." }
            }
            ;

            // Get Navigation ID
            string navigation_id = WebTools.GetNavigationId(context);

            if (string.IsNullOrEmpty(navigation_id))
            {
                return new { error = "No X-App-Key specified" }
            }
            ;

            // Retrieve DataService
            if (dataservices == null || dataservices.Count == 0)
            {
                return new { error = "Data Services not provided" }
            }
            ;
            SQL db = (SQL)dataservices.FirstOrDefault();

            if (db == null)
            {
                return new { error = "Data Service not provided" }
            }
            ;

            // Get filepath
            string uploadFolder = WebTools.Get(context, "folder");

            if (string.IsNullOrEmpty(uploadFolder) == true)
            {
                return new { error = "No folder specified" }
            }
            ;

            // Get File
            IList <string> result = new List <string>();
            var            files  = context.Request.Form.Files;

            foreach (var file in files)
            {
                var parameters = new Dictionary <string, object>();

                parameters[filepathCol] = Path.Combine(uploadFolder, file.FileName);

                // copy file stream to byte array
                using (var uploadStream = file.OpenReadStream())
                {
                    uploadStream.Seek(0, SeekOrigin.Begin);
                    using (var reader = new BinaryReader(uploadStream))
                        parameters[contentCol] = reader.ReadBytes((int)uploadStream.Length);

                    // save to SQL
                    db.Execute($@"
                        BEGIN TRAN
                           UPDATE {table} SET {filepathCol} = @{filepathCol}, {contentCol} = @{contentCol}    
                           WHERE {filepathCol} = @{filepathCol}
                           IF @@rowcount = 0
                           BEGIN
                              INSERT INTO {table} ({filepathCol}, {contentCol}) values (@{filepathCol}, @{contentCol})
                           END
                        COMMIT TRAN"
                               , parameters);
                }
                result.Add($"{parameters[filepathCol]}");
            }

            return(JsonConvert.SerializeObject(result));
        }
    }
}
示例#10
0
        public static object Run(
            HttpContext context
            , string configuration
            , IList <object> dataservices
            )
        {
            // Get Configuration
            if (string.IsNullOrEmpty(configuration))
            {
                return new { error = "No configuration specified." }
            }
            ;
            JObject config = JsonConvert.DeserializeObject <JObject>(configuration);

            string table = $"{config["table"]}";

            if (string.IsNullOrEmpty(table))
            {
                return new { error = "No table Specified." }
            }
            ;

            string idField = config["id"]?.ToString();

            if (string.IsNullOrEmpty(idField))
            {
                return new { error = "No idField Specified." }
            }
            ;

            // Get Navigation ID
            string navigation_id = context.Request.Headers["X-App-Key"];

            if (string.IsNullOrEmpty(navigation_id))
            {
                return new { error = "No X-App-Key specified" }
            }
            ;

            // Retrieve DataService
            if (dataservices == null || dataservices.Count == 0)
            {
                return new { error = "Data Services not provided" }
            }
            ;
            SQL db = (SQL)dataservices.FirstOrDefault();

            if (db == null)
            {
                return new { error = "Data Service not provided" }
            }
            ;

            // Form document
            string id = WebTools.Get(context, idField);

            // check if the record exists
            var param = new Dictionary <string, object>();

            param["id"]            = id;
            param["navigation_id"] = navigation_id;
            string sql = $"SELECT * FROM {table} WHERE {idField}=@id AND navigation_id=@navigation_id";

            // check if admin
            if (config["admin"] != null && config["admin"].ToObject <bool>() == true)
            {
                sql = $"SELECT * FROM {table} WHERE {idField}=@id";
            }

            var results = db.Query(sql, param);

            if (results != null && results.Count() == 1)
            {
                // delete
                return(new { result = Delete(db, table, id, idField) });
            }

            return(new { error = "no record found" });
        }
示例#11
0
        public static object Run(
            HttpContext context
            , string configuration
            , IList <object> dataservices
            )
        {
            // Get Configuration
            if (string.IsNullOrEmpty(configuration))
            {
                return new { error = "No configuration specified." }
            }
            ;
            JObject config = JsonConvert.DeserializeObject <JObject>(configuration);

            // check parameters
            string folder = $"{config["folder"]}"; if (string.IsNullOrEmpty(folder) == true)

            {
                return new { error = "No folder specified." }
            }
            ;

            // Get Navigation ID
            string navigation_id = WebTools.GetNavigationId(context);

            if (string.IsNullOrEmpty(navigation_id))
            {
                return new { error = "No X-App-Key specified" }
            }
            ;

            // Get upload folder
            string uploadFolder = Path.Combine(folder, WebTools.Get(context, "folder"));

            if (string.IsNullOrEmpty(uploadFolder) == true)
            {
                return new { error = "No folder specified" }
            }
            ;

            // Get File
            IList <string> result = new List <string>();
            var            files  = context.Request.Form.Files;

            foreach (var file in files)
            {
                string uploadPath = Path.Combine(uploadFolder, file.FileName);

                using (var fileStream = File.Create(uploadPath))
                {
                    var uploadStream = file.OpenReadStream();
                    uploadStream.Seek(0, SeekOrigin.Begin);
                    uploadStream.CopyTo(fileStream);
                }
                result.Add(uploadPath);
            }

            return(JsonConvert.SerializeObject(result));
        }
    }
}