Пример #1
0
    static void Main(string[] args)
    {
        var Json = new JavaScriptSerializer();

        // Create output directory
        var path = "amosdump-" + protect + "-" + DateTime.Now.ToString("yyMMddHHmmss") + "/";
        Directory.CreateDirectory(path);

        // Database
        using (var conn = new SqlConnection(databaseConnectionString)) {
            conn.Open();

            using (var tw = new StreamWriter(path + "/objects.txt", false)) {
                Console.WriteLine("Indexing objects...");
                using (var cmd = new SqlCommand("SELECT * FROM [obj];", conn)) {
                    using (var rdr = cmd.ExecuteReader()) {
                        while (rdr.Read()) {
                            Console.WriteLine("Object: " + rdr["oid"]);
                            var item = new Dictionary<string, object>();

                            for (var i = 0; i < rdr.FieldCount; i++) {
                                var k = rdr.GetName(i);
                                var v = rdr[i];

                                if (k == "properties") v = Json.Deserialize<Dictionary<string, object>>((string)v);

                                item[k] = v;
                            }

                            tw.WriteLine(Json.Serialize(item) + "\n");
                        }
                    }
                }

                tw.Close();
            }
        }

        // Blob
        using (var tw = new StreamWriter(path + "/resources.txt", false)) {
            Console.WriteLine("Indexing resources...");
            var container = new BlobContainer(blobConnectionString, blobContainerName);
            var map = container.GetReferenceHashMap();
            foreach (var mapItem in map) {
                Console.WriteLine("Resource: " + mapItem.Key);

                // Open blob
                var blob = container.Get(mapItem.Key);

                // Note meta
                var meta = new Dictionary<string, object>(){
                    {"reference", mapItem.Key},
                    {"fileName", blob.GetFilename()},
                    {"md5",mapItem.Value},
                    {"contentType", blob.Properties.ContentType}
                };

                // Store meta
                tw.WriteLine(Json.Serialize(meta) + "\n");
                tw.Flush();

                // Download blob
                blob.DownloadToFile(path + mapItem.Key);
            }

            tw.Close();
        }
        return;
    }
Пример #2
0
        public void ProcessRequest(HttpContext context)
        {
            try {
                // Determine target instance
                Instance instance = null;
                try {
                    instance = Instances.Current;
                } catch (InvalidInstanceException) {
                    fail("channel.baddomain", "Domain '" + context.Request.Url.Host + "' does not have any associated content");
                }

                // Check session is active (have they created a session, and have a valid SID?)
                if (!Session.Active) {
                    fail("channel.nosession", "Session not started or valid");
                    return;
                }

                // Check we are secure (except if AllowInsecure,
                if (!context.Request.IsSecureConnection && instance.Configuration.Loader.Secure) {
                    fail("channel.nosecure", "Session not secure - please use https");
                    return;
                }

                // Get params
                var spath = context.Request.Path.Split('/');
                if (spath.Length != 5) {
                    fail("parameter.missing", "Request is missing parameters");
                    return;
                }
                var uid = spath[3];
                var mode = spath[4];

                // Validate UID
                if (!Uids.Validate(uid)) {
                    fail("parameter.invalid", "uid; Invalid UID");
                    return;
                }

                // Load object
                DbxObject obj;
                try {
                    obj = instance.Uid(uid);
                } catch (ObjectNotExistException) {
                    fail("parameter.invalid", "uid; Object not found");
                    return;
                }

                // Check mode
                if (mode != "" && !obj.Subschema.Blob.Modes.ContainsKey(mode)) {
                    fail("parameter.invalid", "mode; Undefined mode");
                    return;
                }

                // Check access
                if (!obj.AccessBlob(Session.Current.Uid, true, false)) {
                    fail("access.read", "Blob access denied");
                    return;
                }

                // Check if resize exists
                if (mode != "" && !ExistsCache.Contains(uid)) {
                    var container = new BlobContainer(instance.Configuration.Object.Blob.ConnectionString, instance.Configuration.Object.Blob.Container);
                    var blob = container.Get(uid + "-" + mode);
                    if (!blob.Exists()) {
                        // Download content
                        //var tempfile = Path.GetTempFileName();
                        //var tempstream = new FileStream(tempfile, FileMode.Create, FileAccess.ReadWrite);
                        var basestream = new MemoryStream();
                        blob = container.Get(uid);
                        blob.DownloadToStream(basestream);

                        switch (obj.Subschema.Blob.Modes[mode].Handler) {
                            case "image":
                                // Abort if not image
                                switch (blob.Properties.ContentType) {
                                    case "image/jpeg":
                                    case "image/png":
                                    case "image/gif":
                                        break;
                                    default:
                                        // Better method?
                                        context.Response.Write(blob.Properties.ContentType);
                                        context.Response.End();
                                        return;
                                }

                                // Load image processor
                                var baseimage = Image.FromStream(basestream);

                                // Load CURRENT sizes
                                double cw = baseimage.Width;
                                double ch = baseimage.Height;

                                // Regenerate all modes
                                foreach (var sel in obj.Subschema.Blob.Modes) {
                                    var selmode = sel.Value;

                                    // Load TARGET sizes (cannot be bigger than these)
                                    int tw = selmode.Width;
                                    int th = selmode.Height;
                                    var resizemode = selmode.Resize;

                                    // Resize ratio
                                    double r = 1;

                                    switch (resizemode) {
                                        case "max":
                                            if (tw / cw > th / ch) { // Width is bigger
                                                r = th / ch;
                                            } else { // Height is bigger
                                                r = tw / cw;
                                            }
                                            break;
                                        case "fill":
                                            if (tw / cw > th / ch) { // Width is bigger
                                                r = tw / cw;
                                            } else { // Height is bigger
                                                r = th / ch;
                                            }
                                            break;
                                        default:
                                            // Bad schema value
                                            break;
                                    }

                                    // Calculate RESULT sizes
                                    int rw = Convert.ToInt32(cw * r);
                                    int rh = Convert.ToInt32(ch * r);

                                    int w = rw < tw ? rw : tw;
                                    int h = rh < th ? rh : th;
                                    int x = rw < tw ? 0 : (tw - rw) / 2;
                                    int y = rh < th ? 0 : (th - rh) / 2;

                                    // Create resized image
                                    var resizedimage = new Bitmap(w, h); // Final canvas size (confirm?)
                                    var graphic = Graphics.FromImage(resizedimage);
                                    graphic.CompositingQuality = CompositingQuality.HighQuality;
                                    graphic.SmoothingMode = SmoothingMode.HighQuality;
                                    graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                                    graphic.DrawImage(baseimage, new Rectangle(x, y, rw, rh));

                                    // Store image
                                    var resizedstream = new MemoryStream();
                                    resizedimage.Save(resizedstream, ImageFormat.Jpeg);
                                    resizedstream.Position = 0;
                                    container.Get(uid + "-" + sel.Key).PutStream(resizedstream, "image.jpg", "image/jpg");
                                }

                                // Mark as existing
                                ExistsCache.Add(uid);
                                break;
                            default:
                                // Bad schema handler
                                break;
                        }
                    }
                }

                // Calculate redirectpath
                var redirectpath = instance.Configuration.Object.Blob.Path + uid;
                if (mode != "") redirectpath += "-" + mode;

                // Redirect to existing object - cache forever // TODO: This method isn't the best for secure content
                context.Response.ExpiresAbsolute = DateTime.Now.AddYears(1);
                context.Response.Expires = 31536000;
                context.Response.CacheControl = "private";
                context.Response.Cache.SetCacheability(HttpCacheability.Private);
                context.Response.RedirectPermanent(redirectpath, true);
            } catch (UserErrorException e) {
                // Fail nicely with user issues
                fail(e.Type, e.Message);
            } catch (System.Threading.ThreadAbortException) {
            } catch (Exception e) {
                // Fail bluntly with our issues

                Log.Exception(Session.Current.Tid, Session.Current.Sid, Session.Current.Uid, e.GetType().ToString(), e.Source, e.TargetSite.ToString(), e.Message, e.StackTrace);

                // Dump generic error
                fail("unspecified", "A serverside error has occured");
            }
        }
Пример #3
0
        public void SetBlob(string srcuid, BlobDetails blob)
        {
            var request = HttpContext.Current.Request;

            // Check blob is present
            if (null == blob) throw new UserErrorException("parameter.missing", "Missing blob data");

            // Check access
            var userLevel = UserLevel(srcuid);
            if (!AccessBlob(srcuid, false, true)) throw new UserErrorException("access.write", "Access violation attempt while write object (object level " + UserLevel(srcuid) + ")");

            // Check data constraints
            if (Subschema.Blob.ContentTypes.Count > 0 && !Subschema.Blob.ContentTypes.ConvertAll(d => d.ToLower()).Contains(blob.ContentType.ToLower())) {
                var err = "This file type is not supported. The following types are supported: ";
                foreach (var type in Subschema.Blob.ContentTypes) err += type + ", ";
                throw new UserErrorException("blob.badtype", err.substr(0, -2));
            }
            if (blob.Length < Subschema.Blob.MinSize) throw new UserErrorException("blob.toosmall", "File too small, must be at least " + Math.Round((double)Subschema.Blob.MinSize / 1024, 1) + "KB");
            if (blob.Length > Subschema.Blob.MaxSize) throw new UserErrorException("blob.toolarge", "File too large, must be no more than " + Math.Round((double)Subschema.Blob.MaxSize / 1024, 1) + "KB");

            // Open blob store
            var container = new BlobContainer(instance.Configuration.Object.Blob.ConnectionString, instance.Configuration.Object.Blob.Container);

            // Store file
            container.Get(magicUid).PutStreamCacheForever(blob.Stream, blob.Filename, blob.ContentType);
            //blobProps = store.GetProperties(magicUid); // Cache properties

            // Write
            Write();

            // Return stream
            blob.Stream.Position = 0;
        }
Пример #4
0
        public override void StaticRender(string path, HttpContext context)
        {
            // Detect search indexing and give content
            if (String.IsNullOrWhiteSpace(path)) {
                var sb = new StringBuilder();
                sb.AppendLine("<!DOCTYPE html>");
                sb.AppendLine("<html>");
                sb.AppendLine("<head>");
                sb.AppendLine("    <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />");
                sb.AppendLine("    <title>Mission Platform</title>");
                sb.AppendLine("    <meta name=\"viewport\" content=\"initial-scale=1,maximum-scale=3\" />");
                sb.AppendLine("</head>");
                sb.AppendLine("<body style=\"margin: 0\">");
                sb.AppendLine("    <div id=\"p\">");
                sb.AppendLine("        <style type=\"text/css\">");
                sb.AppendLine("            #p {");
                sb.AppendLine("                position: absolute;");
                sb.AppendLine("                height: 100%;");
                sb.AppendLine("                width: 100%;");
                sb.AppendLine("                top: 0;");
                sb.AppendLine("                z-index: 8;");
                sb.AppendLine("                text-align: center;");
                sb.AppendLine("                background: #315473 -webkit-radial-gradient(rgba(255,255,255,.7), rgba(200,200,200,.2) 70%, rgba(0,0,0,0));");
                sb.AppendLine("                background: #315473 -moz-radial-gradient(rgba(255,255,255,.7), rgba(200,200,200,.2) 70%, rgba(0,0,0,0));");
                sb.AppendLine("                background: #315473 -o-radial-gradient(rgba(255,255,255,.7), rgba(200,200,200,.2) 70%, rgba(0,0,0,0));");
                sb.AppendLine("                background: #315473 -ms-radial-gradient(rgba(255,255,255,.7), rgba(200,200,200,.2) 70%, rgba(0,0,0,0));");
                sb.AppendLine("                font: 28px Tahoma;");
                sb.AppendLine("                text-align: center;");
                sb.AppendLine("                color: #fff;");
                sb.AppendLine("                text-shadow: #000 0px 1px 5px;");
                sb.AppendLine("                cursor: default;");
                sb.AppendLine("            }");
                sb.AppendLine("            #p-main {");
                sb.AppendLine("                position: absolute;");
                sb.AppendLine("                top: 65%;");
                sb.AppendLine("                left: 50%;");
                sb.AppendLine("                height: 200px;");
                sb.AppendLine("                width: 200px;");
                sb.AppendLine("                margin: -100px 0 0 -100px;");
                sb.AppendLine("                display: none;");
                sb.AppendLine("            }");
                sb.AppendLine("            #p-status {");
                sb.AppendLine("                margin: 0 0 10px 0;");
                sb.AppendLine("                text-align: center;");
                sb.AppendLine("                font-size: 18px;");
                sb.AppendLine("                color: #fff;");
                sb.AppendLine("            }");
                sb.AppendLine("            #logo {");
                sb.AppendLine("                width: 310px;");
                sb.AppendLine("                height: 134px;");
                sb.AppendLine("                margin: 15% 0 0 0;");
                sb.AppendLine("            }");
                sb.AppendLine("            #p-msg {");
                sb.AppendLine("                font-size: 11px;");
                sb.AppendLine("                text-decoration: none;");
                sb.AppendLine("            }");
                sb.AppendLine("        </style>");
                sb.AppendLine("        <img id=\"logo\" src=\"http://missionplatform.blob.core.windows.net/missionplatform-com/loader_logo.png\" alt=\"\" />");
                sb.AppendLine("        <div id=\"p-main\">");
                sb.AppendLine("            <div id=\"p-status\">");
                sb.AppendLine("                Loading...");
                sb.AppendLine("            </div>");
                sb.AppendLine("        </div>");
                sb.AppendLine("        <div id=\"p-msg\">");
                sb.AppendLine("            <p>Mission Platform connects those who want to get involved in mission with those who are already doing it.</p>");

                var initiativeUids = instance.Index.AllUids("initiative");
                foreach (var initiativeUid in initiativeUids) {
                    var reference = initiativeUid.Substring(initiativeUid.IndexOf('$') + 1);
                    var title = (string)instance.Index.GetProperty(initiativeUid, "title").Pop();
                    var summary = (string)instance.Index.GetProperty(initiativeUid, "caption").Pop();
                    sb.AppendLine("             <p><a href=\"http://missionplatform.com/" + reference + "\"><strong>" + title + "</strong><br />" + Util.EncodeHTML(summary) + "</a>");
                }
                sb.AppendLine("        </div>");
                sb.AppendLine("        ");
                sb.AppendLine("    </div>");
                sb.AppendLine("</body>");
                sb.AppendLine("</html>");

                context.Response.Write(sb.ToString());
                return;
            }

            var spath = path.Split('/');

            // Calculate UID
            var uid = "initiative$" + spath[0];

            // Reject bad UIDs
            if (!Uids.Validate(uid)) {
                context.Response.Write("<p>Invalid path</p>");
                return;
            }

            // Load initiative
            DbxObject obj;
            try {
                obj = instance.Uid(uid);
            } catch (ObjectNotExistException) {
                context.Response.Write("<p>Initiative no longer exists</p>");
                return;
            }

            var mode = "page";
            if (spath.Length > 1) mode = spath[1];

            switch (mode) {
                case "page":
                    // Header
                    var title = obj.GetProp("title", "").ToString();
                    context.Response.Write("<!DOCTYPE html><html><head><title>" + title + " - Mission Platform</title></head><style type=\"text/css\">body{background: #315473; font: 13px/1.5 Helvetica Neue,Arial,Helvetica,\'Liberation Sans\',FreeSans,sans-serif; color: #fff}</style><body><h1>" + title + "</h1>");

                    // Image
                    if (null != obj.GetProp("impression", "")) context.Response.Write("<img src=\"/" + spath[0] + "/impression\" alt=\"" + title + "\" style=\"max-width: 800px;max-height: 800px;\" />");

                    // Summary
                    var summary = obj.GetProp("summary", "").ToString();
                    context.Response.Write("<p>" + summary + "</p>");

                    // Footer
                    context.Response.Write("</body></html>");
                    break;
                case "impression":
                    var impressionuid = obj.GetProp("impression", "system").ToString();
                    if (null != impressionuid) {
                        context.Response.ClearContent();
                        var container = new BlobContainer(instance.Configuration.Object.Blob.ConnectionString, instance.Configuration.Object.Blob.Container);
                        container.Get(impressionuid).DownloadToStream(context.Response.OutputStream);
                    } else {
                        context.Response.StatusCode = 404;
                        context.Response.Write("Initiatve does not have an impression image");
                    }
                    break;
                default:
                    context.Response.Write("<p>Invalid path</p>");
                    break;
            }
        }
Пример #5
0
        static void Main()
        {
            var sourcesystem = new DirectoryInfo(RunSettings.Default.SourceSystem);// "C:\\Users\\Ben\\Documents\\InvertedTomato\\Projects\\AmosJS\\"
            var sourceproject = new DirectoryInfo(RunSettings.Default.SourceProject);//"C:\\Users\\Ben\\Documents\\InvertedTomato\\Clients\\KBP\\kbp.amos\\"
            var domain = RunSettings.Default.TargetDomain; // "devi.kidspb.com";

            // Load form
            Application.SetCompatibleTextRenderingDefault(false);
            main = new Main();
            main.Show();
            Handler.Log("", "Loading...", 0);
            Handler.Log("", "SourceSystem: " + sourcesystem, 0);
            Handler.Log("", "SourceProject: " + sourceproject, 0);
            Handler.Log("", "Domain: " + domain, 0);
            Application.DoEvents();

            // Load worker
            var stopwatch = new System.Diagnostics.Stopwatch();
            stopwatch.Start();
            Engine = new Engine(sourceproject, sourcesystem);
            if (File.Exists(sourceproject + "loader.html")) {
                Loader = new Loader(new FileInfo(sourceproject + "loader.html"), new FileInfo(sourcesystem + "loader.js"));
            } else {
                Loader = new Loader(new FileInfo(sourcesystem + "loader.html"), new FileInfo(sourcesystem + "loader.js"));
            }
            Config = new Config(new FileInfo(sourceproject + "amos.json"));
            stopwatch.Stop();
            Handler.Log("Startup", "Startup scan completed", stopwatch.ElapsedMilliseconds);

            // Check target domain is valid
            ConfigurationDomain domainconfig = null;

            try {
                domainconfig = Config.Configuration.Domain(domain);
            } catch (InvalidDomainException) {
                MessageBox.Show("Compiler configuration error:\n\nSpeficied target domain not defined in configuration. Have you set this domain correctly?");
                Application.Exit();
                return;
            }

            if (Config.Configuration.ObjectsDefinitions.Count == 0) {
                MessageBox.Show("Amos.json configuration error:\n\nNo Object definitions found.");
                Application.Exit();
                return;
            }
            if (Config.Configuration.ResourcesDefinitions.Count == 0) {
                MessageBox.Show("Amos.json configuration error:\n\nNo Resource definitions found.");
                Application.Exit();
                return;
            }
            if (Config.Configuration.SessionsDefinitions.Count == 0) {
                MessageBox.Show("Amos.json configuration error:\n\nNo Session definitions found.");
                Application.Exit();
                return;
            }

            try {
                Config.Configuration.Object = Config.Configuration.ObjectsDefinitions[domainconfig.Objects];
            } catch (Exception) {
                MessageBox.Show("Amos.json configuration error:\n\nSpecified Object definition for domain '" + domain + "' not found.");
                Application.Exit();
                return;
            }
            try {
                Config.Configuration.Resource = Config.Configuration.ResourcesDefinitions[domainconfig.Resources];
            } catch (Exception) {
                MessageBox.Show("Amos.json configuration error:\n\nSpecified Resource definition for domain '" + domain + "' not found.");
                Application.Exit();
                return;
            }
            try {
                Config.Configuration.Session = Config.Configuration.SessionsDefinitions[domainconfig.Sessions];
            } catch (Exception) {
                MessageBox.Show("Amos.json configuration error:\n\nSpecified Session definition for domain '" + domain + "' not found.");
                Application.Exit();
                return;
            }

            Config.Configuration.MinifyClient = domainconfig.MinifyClient;
            Config.Configuration.DebugClient = domainconfig.DebugClient;

            // Connect to blob container
            var ObjectBlobContainer = new BlobContainer(Config.Configuration.Object.Blob.ConnectionString, Config.Configuration.Object.Blob.Container);
            Config.Configuration.Object.Blob.Path = ObjectBlobContainer.Container.Uri.AbsoluteUri + "/";

            ResourceBlobContainer = new BlobContainer(Config.Configuration.Resource.Blob.ConnectionString, domain.Replace('.', '-'));
            ResourceBlobContainer.Create(true);
            BlobPathResource = Config.Configuration.Resource.Blob.Path = ResourceBlobContainer.Container.Uri.AbsoluteUri + "/";

            // Inital run
            Handler.Ready = true;
            Handler.Change();

            // Start resources
            Resources.Start(new DirectoryInfo(sourceproject + "res\\"), new DirectoryInfo(sourcesystem + "res\\"));

            // Show form
            Application.EnableVisualStyles();
            Application.Run(main);
        }