Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Sep 1, 2018

S3 Direct Upload Python Django

Using Pyhton Boto API, we can interact with Amazon S3 servers (for GET, PUT, POST etc)
We can also directly upload files to Amazon S3 from the client browser using Browser Uploads to S3 using HTML POST Forms.

Ref:
https://aws.amazon.com/articles/Java/1434

Prerequisites:
S3_BUCKET
S3_KEY
S3_SECRET
S3_URL

Note:
As per Amazon API, we need to encode policy format to base64 and further generate signature with SHA1
Both Policy and Signature need to be posted
Expiration : You can define the expiration time
acl: public-read/private
$key: upload path startes with
Check the POST S3 Url in HTML
Once the document is successfully uploaded to S3, S3 URL is shown on the page

Django Pyhton View:

import base64
import hmac, hashlib
import re

def direct_s3_upload(request):
  my_bucket = None
  policy_document = None
  policy_base_64 = signature = cors_xml = ""
  try:
    policy_document = '{"expiration": "2020-01-01T00:00:00Z", \
                       "conditions": [ \
                         {"bucket": "%s"}, \
                         {"acl": "public-read"}, \
                         ["starts-with", "$key", "uploads/"], \
                         ["content-length-range", 0, 524288000] \
                       ] \
                    }' % (<S3_BUCKET>)

    whitespace = re.compile(r'\s+')
    policy_document = whitespace.sub('', policy_document)
    policy_base_64 = base64.b64encode(whitespace.sub('', policy_document))
    signature = base64.b64encode(hmac.new(S3_SECRET, policy_base_64, hashlib.sha1).digest()) 
    dic1 = { 
           'MY_BUCKET_NAME': <S3_BUCKET>,
           'MY_AWS_KEY_ID': <S3_KEY>, 
           'MY_POLICY' : policy_base_64,
           'MY_SIGNATURE' : signature,
        }
  except:
    write_exception("direct_s3_upload")
  return render_to_response('test_s3_upload.html', context_instance=RequestContext(request, dic1))


HTML:  (test_s3_upload.html)
<html> 
  <head>
    <title>S3 POST Form</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script>
      var bucketName = '{{MY_BUCKET_NAME}}';
      var AWSKeyId   = '{{MY_AWS_KEY_ID}}';
      var policy     = '{{MY_POLICY}}';
      var signature  = '{{MY_SIGNATURE}}';

      function S3ToolsClass() {
        var _handle_progress = null;
        var _handle_success  = null;
        var _handle_error    = null;
        var _file_name       = null;

        this.uploadFile = function(file, progress, success, error) {
          _handle_progress = progress;
          _handle_success  = success;
          _handle_error    = error;
          _file_name       = file.name;

          console.log(file.name)
          var fd = new FormData();
          fd.append('key', "uploads/" + file.name);
          fd.append('AWSAccessKeyId', AWSKeyId);
          fd.append('acl', 'public-read');
          fd.append('policy', policy);
          fd.append('signature', signature);
          fd.append("file",file);

          var xhr = new XMLHttpRequest({mozSystem: true});
          xhr.upload.addEventListener("progress", uploadProgress, false);
          xhr.addEventListener("load", uploadComplete, false);
          xhr.addEventListener("error", uploadFailed, false);
          xhr.addEventListener("abort", uploadCanceled, false);
          xhr.open('POST', 'https://s3.amazonaws.com/' + bucketName + '/');

          xhr.send(fd);
        }

        function uploadProgress(evt) {
          if (evt.lengthComputable) {
            var percentComplete = Math.round(evt.loaded * 100 / evt.total);
            _handle_progress(percentComplete);
          }
        }

        function uploadComplete(evt) {
          if (evt.target.responseText == "") {
            console.log("Upload complete - success") 
            _handle_success(_file_name);
          } else {
            console.log("Upload complete - not success") 
            _handle_error(evt.target.responseText);
          }
        }

        function uploadFailed(evt) {
          console.log("upload Failed")
          _handle_error("There was an error attempting to upload the file." + evt);
        }

        function uploadCanceled(evt) {
          console.log("upload cancelled")
          _handle_error("The upload has been canceled by the user or the browser dropped the connection.");
        }
      }
      var S3Tools = new S3ToolsClass();
      
      function uploadFile() {
        var file = document.getElementById('file').files[0];
        S3Tools.uploadFile(file, handleProgress, handleSuccess, handleError);
      }

      function handleProgress(percentComplete) {
        document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
      }

      function handleSuccess(fileName) {
        document.getElementById('progressNumber').innerHTML = 'Done!';
        document.getElementById('resultant_s3_url').innerHTML = 'https://s3.amazonaws.com/' + bucketName + '/uploads/' + fileName;
      }

      function handleError(message) {
        document.getElementById('progressNumber').innerHTML = 'Error: ' + message;
      }
    </script>
  </head>
  <body>
    <form id="form" enctype="multipart/form-data" method="post">
      <div class="row">
        1. Select a File<br>
        <input type="file" name="file" id="file"/>
      </div>
      <br>
      <div class="row">
        2. Upload File<br>
        <input type="button" onclick="uploadFile()" value="Upload" />
        <br/>
        <span id="progressNumber"></span>
      </div>
    </div>
    <br>
    <div class="row">
      3. Result S3 Url
      <br>
      <div id="resultant_s3_url"> </div>

    </div>
  </body>
</html>
Thank you for reading this article.

Jun 10, 2018

AWS Cognito SDK using JavaScript

Here is my first script for signup on AWS Cognito using Javascript SDK

AWS Cognito SDK:

https://github.com/amazon-archives/amazon-cognito-identity-js/tree/master/dist


Script:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
</head>
<body>
    <script type='text/javascript' src="aws-cognito-sdk.js"></script>
    <script type='text/javascript' src="amazon-cognito-identity.js"></script>
    <script>
        var data = {
            UserPoolId: 'us-east-XXXXXXXX',     // Insert your user pool id
            ClientId: 'XXXXXXXXXX' // Insert your app client id
        };
        var userPool = new AmazonCognitoIdentity.CognitoUserPool(data);
    </script>
    <fieldset>
        <legend>Cognito Sign Up User Demo</legend>
        User name: <input type="text" id="username" placeholder="Enter user name...">
        <br>
        <br>
        Password: <input type="text" id="password" placeholder="Enter password...">
        <br>
        <br>
        <div style="width:500px;">
            <button id="signupUser">Sign Up User</button>
        </div>
        <ul id="signupUserResults"></ul>
    </fieldset>
    <script>
        var attributeList = [];
        document.getElementById('signupUser').addEventListener('click', function () {
          userPool.signUp(document.getElementById('username').value, document.getElementById('password').value,
            attributeList, null,
            function (err, result) {
                if (err) {
                    alert(err);
                    return;
                }
                document.getElementById('signupUserResults').innerHTML = "Results: " + JSON.stringify(
                  result.user, null, 2);
                cognitoUser = result.user;
                console.log(cognitoUser);
            });
        });
    </script
</body>
</html>

Jul 20, 2015

Jquery Examples

MAP
$.map([10,20,30], function(n,i) { return n+i;});   //[10, 21, 32]

Jquery Reverse Order of  Child Elements (ul & li):
var list = $('ul');
var listItems = list.children('li');
list.append(listItems.get().reverse());

$('ul li')[0]                       //<li>AAA</li>
$('ul li')[0].innerHTML  //AAA


$("ul li").eq(7).css("border", "1px solid #000000");  //Applies style to 8th element

Apply Style to Even & Odd rows:
$("ul  li:even").addClass("even");
$("ul  li:odd").addClass("odd");
(or)

$("ul li").each(function(i) {
if (i % 2 == 1)
{
    $(this).addClass("odd");    //$(this).css("background-color", 'red')
}
else
{
    $(this).addClass("even");   //$(this).css("background-color", 'yellow')
}
});

if ($('#elem').is(':hidden')) {
   // Do something conditionally
}

$('p:visible').hide();  // Hiding only elements that are currently visible
$('ul').siblings().length   //Siblings of <ul> element

To Get Immediate Children
<a href="/category">Category</a>
<ul id="nav">
<li><a href="#anchor1">Anchor 1</a></li>
<li><a href="#anchor2">Anchor 2</a></li>
<li><span><a href="#anchor3">Anchor 3</a></span></li>
</ul>

$('li > a').length => 2 (only in immediate direct children)
$('li a').length => 3 (all anchor tags )

$('li').children()
or
$('li > *')
or
$('li').find('> *')

Stop Event Bubbling:
return false; => event.stopPropagation(); + event.preventDefault();
event.stopImmediatePropagation(); => stops immediately without executing handlers of same element.
event.stopPropagation(); => stops executing handlers of parent elements, but executes that of same element

end()
You can return to the previous set of DOM elements that were selected before using a destructive method.

   <p>text 1 </p>
    <p class="test_class">text 2
        <span>AAA</span>
    </p>
    <p>text 3 </p>
   
    <script type="text/JavaScript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
    <script type="text/JavaScript">
        console.log($('p').filter('.test_class').length); // 1
        console.log($('p').filter('.test_class').end().length); // 3
        console.log($('p').filter('.test_class').find('span').end().end().length); // 3
    </script>

filter() vs find()
find() will operates the children of the current set
filter() will only operate on the current set of elements.

On the same level: (FILTER)
$('div').filter('.x').length
or
$('div.x').text()

Inner level search (FIND)
$('div').find('.x').length
or
$('div .x').text()

Jquery - Save File:
$('#ajax-loader').show();
            $.post("/test/return/data/", snddata,
                  function callbackHandler(data, textstatus){
                    $('#ajax-loader').hide();
                    if(data.status == 1){
                        str = data.encrypted_data
                        saveData(str, "download_file_name")
                    }
                    else{
                       alert(data.msg);
                    }
                 },
                 "json"
            );

var saveData = (function () {
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.style = "display: none";
        return function (data, fileName) {
            var json = data,
                blob = new Blob([json], {type: "octet/stream"}),
                url = window.URL.createObjectURL(blob);
            a.href = url;
            a.download = fileName;
            a.click();
            window.URL.revokeObjectURL(url);
        };
      }());


&amp issues while passing from template to server
str = ''
document.location = '/test/url/' + encodeURIComponent(str);

!important
!important (It will override the CSS definition in header classes)
<style type="text/css">
   .bst_popover{
     max-width: 500px !important;
   }
</style>

Choose a specific parent
$(this).parents("tr:first");
$(this).closest("tr");


Jun 28, 2013

Execute Perl or Python or PHP online

I come across a very good site where you can run perl online and see the results.

http://www.compileonline.com/execute_perl_online.php

Advantages:
Just write the code (in the left panel) and run on the fly.
If case of any errors, it is shown on the right panel
They also prive an input.txt (in one of the tab) and practice reading/writing files
When you click on Multiple Files, it also gives support.pm, we can practice package concepts.

You can also run online Python/PHP/Java/Shell/JavaScript/HTML etc.,

Python:
http://www.compileonline.com/execute_python3_online.php

PHP:
http://www.compileonline.com/execute_php_online.php

Java:
http://www.compileonline.com/compile_java_online.php

Shell Scripting:
http://www.compileonline.com/execute_ksh_online.php

Java Script:
http://www.compileonline.com/try_javascript_online.php

HTML:
http://www.compileonline.com/try_html5_online.php

and many more on home page

http://www.compileonline.com/