Javascript path to AWS bucket 0 using jPlayer? - javascript

I have two blocks of code. They both work together to list and play MP3 files from my AWS S3 Container bucket. But I cannot figure out the path to the "Album Cover" (i.e. Poster). KEEP IN MIND, each album folder contains a poster image that is the same name as the folder with a jpg extension. For example, see below:
Folder name: Beatles-Greatest-Hits
Folder Contents:
song01.mp3
song02.mp3
song03.mp3
Beatles-Greatest-Hits.jpg
This blocks works fine connects to the bucket: II realize it is long, but I am trying the find the path to the poster, so I included it all.
<script type="text/javascript">
var AWS_AccessKeyId = 'MY-KEY-HERE';
var AWS_SecretAccessKey = 'MY-SECRET-HERE';
var AWS_Region = 'REGION-HERE';
var AWS_BucketName = 'musicpax';
var AWS_MaxKeys = 500;
var AWS_Prefix = 'mpx_music/';
var AWS_SignedUrl_Expires = 900;
</script>
<!-- ***** ///////////////////////// ***** -->
<!-- ***** AWS DISPLAY & LIST SCRIPT ***** -->
<!-- ***** ///////////////////////// ***** -->
<script type="text/javascript">
AWS.config.update({accessKeyId: AWS_AccessKeyId, secretAccessKey: AWS_SecretAccessKey});
AWS.config.region = AWS_Region;
var bucket = new AWS.S3({params: {Bucket: AWS_BucketName}});
function listMoreObjects(marker, prefix, countFiles, countFolders) {
$('#overlay').show();
$('#status').html('<div id="statusimg"></div>Loading...');
bucket.listObjects({MaxKeys: AWS_MaxKeys, Marker: marker, Prefix : prefix, Delimiter : '/' },function (err, data) {
if (err) {
$('#status').html('<img src="img/exclamation-red.png"> Could not load objects from S3');
} else {
var truncated = data.IsTruncated;
var nextMarker = data.NextMarker;
$('#moreobjects').remove();
renderObjects(data.Contents, countFolders, countFiles, prefix, truncated, nextMarker);
}
$('#overlay').hide();
});
};
function listObjects(prefix) {
$('#overlay').show();
$('#status').html('<div id="statusimg"></div>Loading...');
$('#objects').empty();
bucket.listObjects({MaxKeys: AWS_MaxKeys, Prefix : prefix, Delimiter : '/' },function (err, data) {
if (err) {
$('#status').html('<img src="img/exclamation-red.png"> Could not load objects from S3');
} else {
//Load folders...
//Set breadcrumbs..
var truncated = data.IsTruncated;
var nextMarker = data.NextMarker;
var currentFolder = '<span class="path">root</span>';
var icon = '';
if (prefix !== '') {
currentFolder += '/';
var folders = prefix.split('/');
var parent = '';
var slash = '';
var topFolder = '';
for (var i = 0; i < folders.length - 1; i++) {
if (folders[i] !== '') {
var path = '';
parent += slash + folders[i];
if ( i > 0 ) {
path = parent;
} else {
path = folders[i];
}
if ( i !== (folders.length - 2)) {
topFolder = path;
}
currentFolder += slash + '<span class="path">' + folders[i] + '</span>';
slash = '/';
}
}
}
if (typeof topFolder != 'undefined') {
if (topFolder !== '') {
topFolder += '/';
}
icon = '<img src="img/arrow-090.png"/>'
// $('#objects').append('<li>' + icon + '<span>...</span></li>');
$('#objects').append('<li>' + '<span>...</span></li>');
}
$('#breadcrumb').html('Current folder is : ' + currentFolder);
//Set folders...
var countFolders = 0;
for (var i = 0; i < data.CommonPrefixes.length; i++) {
var currentPrefix = data.CommonPrefixes[i].Prefix;
var name = (currentPrefix.replace(prefix, '')).replace('/','');
icon = '<img src="img/folder-horizontal.png"/>'
if (prefix !== currentPrefix) {
countFolders++;
// $('#objects').append('<li style="list-style:none;margin-left:-40px;border:1px solid #00f;">' + icon + '<span>' + name + '</span></li>');
$('#objects').append('<li style="list-style:none;padding: 5px 0;margin-left:-40px;border:1px solid #00f;">' + '<span>' + name + '</span></li>');
}
}
renderObjects(data.Contents, countFolders, 0, prefix, truncated, nextMarker);
}
//$('#overlay').hide();
});
};
function renderObjects(contents, countFolders, currentCountFiles, prefix, truncated, nextMarker) {
//Load files...
var countFiles = currentCountFiles;
for (var i = 0; i < contents.length; i++) {
var key = contents[i].Key;
var size = Math.ceil(contents[i].Size / 1024);
var fileName = key.replace(prefix, '');
// icon = '<img src="img/document.png"/>'
if (prefix !== key) {
countFiles++;
var params = {Bucket: 'bucket', Key: 'key'};
$('#objects').append('<li style="list-style:none;">' + icon + '<span>' + fileName + '</span></li>');
}
}
if (truncated) {
$('#status').html('Loaded : ' + countFolders + ' folder(s), showing ' + countFiles + ' item(s) from S3, <img src="img/arrow-270.png">Go to the bottom of the list to load more items.');
// icon = '<img src="img/plus-circle.png"/>'
$('#objects').append('<li id="moreobjects">' + icon + '<span>Get more items...</span></li>');
} else {
$('#status').html('Loaded : ' + countFolders + ' folder(s), ' + countFiles + ' item(s) from S3');
}
}
function getObject(key) {
var params = {Bucket: AWS_BucketName, Key: key, Expires: AWS_SignedUrl_Expires};
var url = bucket.getSignedUrl('getObject', params);
return url;
//window.open(url, url);
}
function scrollToBottomListObjects() {
$('#contents').scrollTop($('#contents').prop("scrollHeight"));
}
function init() {
$('#headertitle').html(TITLE);
}
$( document ).ready(function() {
init();
listObjects(AWS_Prefix);
});
</script>
Below is the code that formats the jplayer code. I am trying to get the "Poster" path. If I get it correct, then it will display properly...
bucket.listObjects(
{
MaxKeys: AWS_MaxKeys,
Prefix : '<?php echo $_REQUEST['p']; ?>',
Delimiter : '/'
},
function (err, data)
{
if(data.Contents.length)
{
var prefix = '<?php echo $_REQUEST['p']; ?>';
for(var countAws=1; countAws < data.Contents.length; countAws++)
{
var key = data.Contents[countAws].Key;
var fileName = key.replace(prefix, '');
var linkAws = getObject(key);
var newlinkAws = linkAws.split('?');
var links = newlinkAws[0];
console.log(links);
myPlaylist.add({
title:""+fileName+"",
artist:"Artist",
mp3:links,
oga:links,
poster: ""+currentFolder+"".jpg //<--- HERE IS THE ISSUE
});
}
}
}
)
******* The code "poster: ""+currentFolder+"".jpg" above is where the problem is.
The absolute link to the example I gave above would be:
AWSS3/musicpax/mpx_music/Beatles-Greatest-Hits/Beatles-Greatest-Hits.jpg
But since this is dynamic, I cant use an absolute link. Can you provide any insight from the code at the top - that will lead to the correct path configuration.
Thank you in advance for any help.

This pulled the name from the link (path)... where it says 'HERE'
for(var countAws=1; countAws < data.Contents.length; countAws++)
{
var key = data.Contents[countAws].Key;
var fileName = key.replace(prefix, '');
var linkAws = getObject(key);
var newlinkAws = linkAws.split('?');
var links = newlinkAws[0];
/* Gets Album name HERE */
var album = links;
album = album.split("/");
album_name = (album[4]);
console.log(links);
myPlaylist.add({
title:""+fileName+"",
artist:""+album_name+"",
mp3:links,
oga:links,
poster: " "
});
}

Related

Is it possible to load build result in VS Output window?

I was been trying to switch IDEs.
What if I will want to load MISRA check result file to Visual Studio.
Is there any direct or simpler way?
Made indirect workaround:
var fso = new ActiveXObject("Scripting.FileSystemObject");
var rootPath = fso.GetFolder(".");
var cStat = rootPath.files;
for(var objEnum = new Enumerator(cStat); !objEnum.atEnd(); objEnum.moveNext()) {
var strFileName = objEnum.item();
if (strFileName.ShortName.length - strFileName.ShortName.toUpperCase().indexOf(".TXT") != 4) continue;
//WScript.Echo(strFileName);
break;
}
var ts = strFileName.OpenAsTextStream(1);
while(!ts.AtEndOfStream) {
var textLine = ts.ReadLine();
textLine = textLine.split('\t'); // IAR MISRA line: Description Rule Severity File:Line
if (textLine[3])
{
var res = textLine[3].replace(/(.+):(\d+)/g, "$1($2)");
if (textLine[2] == "Low")
{
res += ": warning " + textLine[1] + ": " + textLine[0];
}
else
{
res += ": error " + textLine[1] + ": " + textLine[0] + ' ' + textLine[2];
}
WScript.Echo(res);
}
}
ts.Close();
Using fake NMAKE project with build command like cscript /NoLogo PrintLog.js.
Now I can open files reported by MISRA in VS by copying export txt file to this project and running build.
Similar older IAR warning(s) filter used as pipe by command:
...\iarbuild "project.ewp" ReleaseCfg | cscript /NoLogo IARfilterPipe.js.
var fso = new ActiveXObject("Scripting.FileSystemObject");
var rootPath = fso.GetFolder(".") + '\\';
var x = oldBad(), skip = {};
for (i in x) skip[x[i]] = 1;
var stat = [0, 0], all = [], newWarnings = [];
do {
var line = WScript.StdIn.ReadLine();
if (line.indexOf('[') > 0) // possible warning line
{
all.push(line);
line = line.replace(rootPath, "");
var fit = 0;
if (line.indexOf("Remark[") > -1)
{
fit++;
stat[0]++;
line = line
.replace(/\d+>\s+/g, "")
.replace(/Remark\[(\S+)\]:/g, "Warning $1:");
}
else if (line.indexOf("Error[") > -1)
{
fit++;
stat[1]++;
line = line
.replace(/\d+>\s+/g, "")
.replace(/Error\[(\S+)\]:/g, "Error $1:");
}
if (skip[line] != 1 && fit)
{
newWarnings.push(line);
WScript.Echo('!' + line);
var m = line.match(/\s*[^\s.]+\.(s|cpp|c)/g)
} else {
WScript.Echo('_' + line);
}
}
else {
var m = line.match(/\s*[^\s.]+\.(s|cpp|c)/g)
if (m == null) // no name.ext
{
WScript.Echo(line);
}
else if (m.length == 1) // single filename
{
all.push(line);
}
}
} while (!WScript.StdIn.AtEndOfStream);
if (all.length)
{
all = all.sort();
writeFile("buildFiles.txt", all.join('\n'));
}
if (newWarnings.length)
{
writeFile("newWarnings.txt", newWarnings.join('\n'));
WScript.Echo("========== New warnings: ==========");
}
for(var l in newWarnings)
{
WScript.Echo(newWarnings[l]);
}
if (stat[0] + stat[1])
{
WScript.Echo("========== Build Result - Warnings " + stat[0] + " Errors " + stat[1] + " ==========");
}
WScript.Quit(0); // (do not work from file after Echo => -1)
function writeFile(filename, content)
{
var TextStream = fso.CreateTextFile(filename);
TextStream.Write(content);
TextStream.Close()
}
function oldBad()
{
return [
'somefile.cpp(42) : Warning Pe340: value copied to temporary, reference to temporary used', ...
];
}

Brainlabs adwords script remove firstpagemaxbid restriction

Can some body help me modify this script.
The purpose of the script is to change bids for the keywords based on average position. One of the assumptions that the script has is that it sets a firstpagebid for the keyword but it won't allow for the bid to go below the firstpagebid even if the position is too high.
Is there a way to remove this restriction? so basically if the new cpc calculated is lower than the first page bid then it allows for the new cpc to be lower than the firstpage bid.
/**
*
* Average Position Bidding Tool
*
* This script changes keyword bids so that they target specified positions,
* based on recent performance.
*
* Version: 1.5
* Updated 2015-09-28 to correct for report column name changes
* Updated 2016-02-05 to correct label reading, add extra checks and
* be able to adjust maximum bid increases and decreases separately
* Updated 2016-08-30 to correct label reading from reports
* Updated 2016-09-14 to update keywords in batches
* Updated 2016-10-26 to avoid DriveApp bug
* Google AdWords Script maintained on brainlabsdigital.com
*
**/
// Options
var maxBid = 14.50;
// Bids will not be increased past this maximum.
var minBid = 3.0;
// Bids will not be decreased below this minimum.
var firstPageMaxBid = 10.00;
// The script avoids reducing a keyword's bid below its first page bid estimate. If you think
// Google's first page bid estimates are too high then use this to overrule them.
var dataFile = "AveragePositionData.txt";
// This name is used to create a file in your Google Drive to store today's performance so far,
// for reference the next time the script is run.
var useFirstPageBidsOnKeywordsWithNoImpressions = true;
// If this is true, then if a keyword has had no impressions since the last time the script was run
// its bid will be increased to the first page bid estimate (or the firsPageMaxBid if that is smaller).
// If this is false, keywords with no recent impressions will be left alone.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Advanced Options
var bidIncreaseProportion = 0.20;
var bidDecreaseProportion = 0.25;
var targetPositionTolerance = 0.3;
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function main() {
var fieldJoin = ",";
var lineJoin = "$";
var idJoin = "#";
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/*var files = DriveApp.getFilesByName(dataFile);
if (!files.hasNext()) {
var file = DriveApp.createFile(dataFile,"\n");
Logger.log("File '" + dataFile + "' has been created.");
} else {
var file = files.next();
if (files.hasNext()) {
Logger.log("Error - more than one file named '" + dataFile + "'");
return;
}
Logger.log("File '" + dataFile + "' has been read.");
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Get the current date/time
var currentTime = new Date(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "MMM dd,yyyy HH:mm:ss"));
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var hourOfDay = currentTime.getHours();
var dayOfWeek = days[currentTime.getDay()]; //Added on 9/21/2015
// Prevent adjustments if not in between 8am and 11pm and Diffrent running time by date - Added on 9/21/2015 (important allows to set time based on day)
switch (dayOfWeek) {
case 'Monday':
case 'Tuesday':
case 'Wednesday':
case 'Thursday':
case 'Friday':
if (hourOfDay < 8 || hourOfDay >= 21) {
Logger.log("Not the Right Time");
return;
}
break;
case 'Saturday':
case 'Sunday':
if (hourOfDay < 8 || hourOfDay >= 18) {
Logger.log("Not the Right Time");
return;
}
break;
}
Logger.log("Right Time");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var labelIds = [];
var labelIterator = AdWordsApp.labels()
.withCondition("KeywordsCount > 0")
.withCondition("LabelName CONTAINS_IGNORE_CASE 'Position '")
.get();
while (labelIterator.hasNext()) {
var label = labelIterator.next();
if (label.getName().substr(0,"position ".length).toLowerCase() == "position ") {
labelIds.push(label.getId());
}
}
if (labelIds.length == 0) {
Logger.log("No position labels found.");
return;
}
Logger.log(labelIds.length + " position labels have been found.");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var keywordData = {
//UniqueId1: {LastHour: {Impressions: , AveragePosition: }, ThisHour: {Impressions: , AveragePosition: },
//CpcBid: , FirstPageCpc: , MaxBid, MinBid, FirstPageMaxBid, PositionTarget: , CurrentAveragePosition:,
//Criteria: }
}
var ids = [];
var uniqueIds = [];
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
var report = AdWordsApp.report(
'SELECT Id, Criteria, AdGroupId, AdGroupName, CampaignName, Impressions, AveragePosition, CpcBid, FirstPageCpc, Labels, BiddingStrategyType ' +
'FROM KEYWORDS_PERFORMANCE_REPORT ' +
'WHERE Status = ENABLED AND AdGroupStatus = ENABLED AND CampaignStatus = ENABLED ' +
'AND LabelIds CONTAINS_ANY [' + labelIds.join(",") + '] ' +
'AND AdNetworkType2 = SEARCH ' +
'AND Device NOT_IN ["HIGH_END_MOBILE"] ' +
'DURING TODAY'
);
var rows = report.rows();
while(rows.hasNext()){
var row = rows.next();
if (row["BiddingStrategyType"] != "cpc") {
if (row["BiddingStrategyType"] == "Enhanced CPC"
|| row["BiddingStrategyType"] == "Target search page location"
|| row["BiddingStrategyType"] == "Target Outranking Share"
|| row["BiddingStrategyType"] == "None"
|| row["BiddingStrategyType"] == "unknown") {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses '" + row["BiddingStrategyType"] + "' rather than manual CPC. This may overrule keyword bids and interfere with the script working.");
} else {
Logger.log("Warning: keyword " + row["Criteria"] + "' in campaign '" + row["CampaignName"] +
"' uses the bidding strategy '" + row["BiddingStrategyType"] + "' rather than manual CPC. This keyword will be skipped.");
continue;
}
}
var positionTarget = "";
if (row["Labels"].trim() == "--") {
continue;
}
var labels = JSON.parse(row["Labels"].toLowerCase()); // Labels are returned as a JSON formatted string
for (var i=0; i<labels.length; i++) {
if (labels[i].substr(0,"position ".length) == "position ") {
var positionTarget = parseFloat(labels[i].substr("position ".length-1).replace(/,/g,"."),10);
break;
}
}
if (positionTarget == "") {
continue;
}
if (integrityCheck(positionTarget) == -1) {
Logger.log("Invalid position target '" + positionTarget + "' for keyword '" + row["Criteria"] + "' in campaign '" + row["CampaignName"] + "'");
continue;
}
ids.push(parseFloat(row['Id'],10));
var uniqueId = row['AdGroupId'] + idJoin + row['Id'];
uniqueIds.push(uniqueId);
keywordData[uniqueId] = {};
keywordData[uniqueId]['Criteria'] = row['Criteria'];
keywordData[uniqueId]['ThisHour'] = {};
keywordData[uniqueId]['ThisHour']['Impressions'] = parseFloat(row['Impressions'].replace(/,/g,""),10);
keywordData[uniqueId]['ThisHour']['AveragePosition'] = parseFloat(row['AveragePosition'].replace(/,/g,""),10);
keywordData[uniqueId]['CpcBid'] = parseFloat(row['CpcBid'].replace(/,/g,""),10);
keywordData[uniqueId]['FirstPageCpc'] = parseFloat(row['FirstPageCpc'].replace(/,/g,""),10);
setPositionTargets(uniqueId, positionTarget);
}
Logger.log(uniqueIds.length + " labelled keywords found");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
setBidChange();
setMinMaxBids();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/* var currentHour = parseInt(Utilities.formatDate(new Date(), AdWordsApp.currentAccount().getTimeZone(), "HH"), 10);
if (currentHour != 0) {
var data = file.getBlob().getDataAsString();
var data = data.split(lineJoin);
for(var i = 0; i < data.length; i++){
data[i] = data[i].split(fieldJoin);
var uniqueId = data[i][0];
if(keywordData.hasOwnProperty(uniqueId)){
keywordData[uniqueId]['LastHour'] = {};
keywordData[uniqueId]['LastHour']['Impressions'] = parseFloat(data[i][1],10);
keywordData[uniqueId]['LastHour']['AveragePosition'] = parseFloat(data[i][2],10);
}
}
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
findCurrentAveragePosition();
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//Batch the keyword IDs, as the iterator can't take them all at once
var idBatches = [];
var batchSize = 5000;
for (var i=0; i<uniqueIds.length; i += batchSize) {
idBatches.push(uniqueIds.slice(i,i+batchSize));
}
Logger.log("Updating keywords");
// Update each batch
for (var i=0; i<idBatches.length; i++) {
try {
updateKeywords(idBatches[i]);
} catch (e) {
Logger.log("Error updating keywords: " + e);
Logger.log("Retrying after one minute.");
Utilities.sleep(60000);
updateKeywords(idBatches[i]);
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Logger.log("Writing file.");
// var content = resultsString();
// file.setContent(content);
Logger.log("Finished.");
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Functions
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function integrityCheck(target){
var n = parseFloat(target, 10);
if(!isNaN(n) && n >= 1){
return n;
}
else{
return -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setPositionTargets(uniqueId, target){
if(target !== -1){
keywordData[uniqueId]['HigherPositionTarget'] = Math.max(target-targetPositionTolerance, 1);
keywordData[uniqueId]['LowerPositionTarget'] = target+targetPositionTolerance;
}
else{
keywordData[uniqueId]['HigherPositionTarget'] = -1;
keywordData[uniqueId]['LowerPositionTarget'] = -1;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function bidChange(uniqueId){
var newBid = -1;
if(keywordData[uniqueId]['HigherPositionTarget'] === -1){
return newBid;
}
var cpcBid = keywordData[uniqueId]['CpcBid'];
var minBid = keywordData[uniqueId]['MinBid'];
var maxBid = keywordData[uniqueId]['MaxBid'];
if (isNaN(keywordData[uniqueId]['FirstPageCpc'])) {
Logger.log("Warning: first page CPC estimate is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
var firstPageBid = Math.min(keywordData[uniqueId]['FirstPageCpc'], keywordData[uniqueId]['FirstPageMaxBid'], maxBid);
var currentPosition = keywordData[uniqueId]['CurrentAveragePosition'];
var higherPositionTarget = keywordData[uniqueId]['HigherPositionTarget'];
var lowerPositionTarget = keywordData[uniqueId]['LowerPositionTarget'];
var bidIncrease = keywordData[uniqueId]['BidIncrease'];
var bidDecrease = keywordData[uniqueId]['BidDecrease'];
if((currentPosition > lowerPositionTarget) && (currentPosition !== 0)){
var linearBidModel = Math.min(2*bidIncrease,(2*bidIncrease/lowerPositionTarget)*(currentPosition-lowerPositionTarget));
var newBid = Math.min((cpcBid + linearBidModel), maxBid);
}
if((currentPosition < higherPositionTarget) && (currentPosition !== 0)) {
var linearBidModel = Math.min(2*bidDecrease,((-4)*bidDecrease/higherPositionTarget)*(currentPosition-higherPositionTarget));
var newBid = Math.max((cpcBid-linearBidModel),minBid);
if (cpcBid > firstPageBid) {
var newBid = Math.max(firstPageBid,newBid);
}
}
if((currentPosition === 0) && useFirstPageBidsOnKeywordsWithNoImpressions && (cpcBid < firstPageBid)){
var newBid = firstPageBid;
}
if (isNaN(newBid)) {
Logger.log("Warning: new bid is not a number for keyword '" + keywordData[uniqueId]['Criteria'] + "'. This keyword will be skipped");
return -1;
}
return newBid;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function findCurrentAveragePosition(){
for(var x in keywordData){
if(keywordData[x].hasOwnProperty('LastHour')){
keywordData[x]['CurrentAveragePosition'] = calculateAveragePosition(keywordData[x]);
} else {
keywordData[x]['CurrentAveragePosition'] = keywordData[x]['ThisHour']['AveragePosition'];
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function calculateAveragePosition(keywordDataElement){
var lastHourImpressions = keywordDataElement['LastHour']['Impressions'];
var lastHourAveragePosition = keywordDataElement['LastHour']['AveragePosition'];
var thisHourImpressions = keywordDataElement['ThisHour']['Impressions'];
var thisHourAveragePosition = keywordDataElement['ThisHour']['AveragePosition'];
if(thisHourImpressions == lastHourImpressions){
return 0;
}
else{
var currentPosition = (thisHourImpressions*thisHourAveragePosition-lastHourImpressions*lastHourAveragePosition)/(thisHourImpressions-lastHourImpressions);
if (currentPosition < 1) {
return 0;
} else {
return currentPosition;
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function keywordUniqueId(keyword){
var id = keyword.getId();
var idsIndex = ids.indexOf(id);
if(idsIndex === ids.lastIndexOf(id)){
return uniqueIds[idsIndex];
}
else{
var adGroupId = keyword.getAdGroup().getId();
return adGroupId + idJoin + id;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setMinMaxBids(){
for(var x in keywordData){
keywordData[x]['MinBid'] = minBid;
keywordData[x]['MaxBid'] = maxBid;
keywordData[x]['FirstPageMaxBid'] = firstPageMaxBid;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function setBidChange(){
for(var x in keywordData){
keywordData[x]['BidIncrease'] = keywordData[x]['CpcBid'] * bidIncreaseProportion/2;
keywordData[x]['BidDecrease'] = keywordData[x]['CpcBid'] * bidDecreaseProportion/2;
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
function updateKeywords(idBatch) {
var keywordIterator = AdWordsApp.keywords()
.withIds(idBatch.map(function(str){return str.split(idJoin);}))
.get();
while(keywordIterator.hasNext()){
var keyword = keywordIterator.next();
var uniqueId = keywordUniqueId(keyword);
var newBid = bidChange(uniqueId);
if(newBid !== -1){
keyword.setMaxCpc(newBid);
}
}
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
/*function resultsString(){
var results = [];
for(var uniqueId in keywordData){
var resultsRow = [uniqueId, keywordData[uniqueId]['ThisHour']['Impressions'], keywordData[uniqueId]['ThisHour']['AveragePosition']];
results.push(resultsRow.join(fieldJoin));
}
return results.join(lineJoin);
}*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
}
As I understand, the script increases the cpcBid when the current average position is too high, and decreases it when the position is too low.
But when the bid is decreased and the previous bid is more than firstPageBid, the new bid will not decrease below firstPageBid.
Remove
if (cpcBid > firstPageBid) {
var newBid = Math.max(firstPageBid,newBid);
}
to allow your new bid to go lower than firstPageBid.

How to get JavaScript variable from MySQL database table?

I want to take a JavaScript var from database to JavaScript code.
I have a twitch community that help stream by the way I need to let the user or member add their twitch name to the list so that other members can see them when they are online.
my code is :
JAVASCRIPT
var hello = "hello";
/* This is an alternate method to creating javascript methods
function streamer(name, status, url) {
this.name = name;
this.status = status;
this.url = url;
} */
// The streamer object
// here we will store the necessary information from
// the twitch api json file
var Streamer = {
id: 0,
status: "title",
name: "strimmah",
display_name: "Strimmah",
url: "https://secure.twitch.tv/freecodecamp", // test url
previewImgs: ["large", "medium", "small", "template"],
game: "GaM3",
viewers: 0,
init: function(name, status, game, url) {
this.name = name;
this.status = status;
this.game = game;
this.url = url;
},
init: function(name, status, game, viewers, url) {
this.name = name;
this.status = status;
this.game = game;
this.viewers = viewers;
this.url = url;
},
initPreviewImgs: function(large, medium, small, template) {
this.previewImgs[0] = large;
this.previewImgs[1] = medium;
this.previewImgs[2] = small;
this.previewImgs[3] = template;
}
};
// delete test variables
var test = Object.create(Streamer);
var backUpImage = "https://static-cdn.jtvnw.net/ttv-static/404_preview-640x360.jpg";
var tempStreamers = [
"nokss68",
"snake606",
"team_itxx_cod",
"relapsegtv",
"sokkaenpyjama",
"elfepurpl3",
"lighthund",
"spacecakezed",
"nagatsu6",
"xng360",
"nazenko",
"giiskaa",
"floki_live",
"kayakox",
"jejen64",
"spivix",
"keryg4n",
"mehdii95150",
"mrgeekyfr",
"zaykerz92",
"etsalutdit",
"x_dyn_x",
"martind32",
"el_fideo11",
"xmisticoxx",
"zookervinc78",
"MrCraaftt",
"killerelite84",
"Aqu0ss",
"panteleimon42",
"veynstream",
"le_salty_gamer"
];
var streamDisplayStatus = 1; // 0-ALL, 1-Online Only, 2-Offline only
var twitchURL = "https://secure.twitch.tv/"; // to create channel urls
var streamerArray = [];
var showOffline = true;
// ENTRY POINT,
$(document).ready(function() {
/*for (var i = 0; i < tempStreamers.length; i++) {
loadStreamJsonInfo(tempStreamers[i], test);
}*/
// initial set of streamers, we start with Overview so show all
instantiateStreamers();
// navigator button setup
navigationButtons();
});
function instantiateStreamers() {
streamerArray.length = 0;
for (var i = 0; i < tempStreamers.length; i++) {
var streamer = Object.create(Streamer);
loadStreamJsonInfo(tempStreamers[i], streamer);
}
}
function loadStreamJsonInfo(name, data) {
/*$.getJSON('https://api.twitch.tv/kraken/streams/freecodecamp?callback=?', function(json) {
console.log(json);
}); */
$.getJSON('https://api.twitch.tv/kraken/streams/' + name + '?callback=?',
function(json) {
// console.log(json);
var stream = json.stream;
if (stream !== null) {
var channel = json.stream.channel;
data.init(channel.display_name, channel.status, channel.game, stream.viewers, channel.url);
data.initPreviewImgs(stream.preview.large, stream.preview.medium, stream.preview.small, stream.preview.template);
// console.log(data.name + " " + data.status + " " + data.viewers);
} else {
data.init(name, "Offline", "", 0, twitchURL + name)
data.initPreviewImgs(backUpImage, backUpImage, backUpImage, backUpImage);
}
streamerArray.push(data);
//console.log("TEST: " + streamerArray.length);
checkDisplayStatus(data);
}); // end of getJson
}
function checkDisplayStatus(data) {
switch (streamDisplayStatus) {
case 0:
createStreamerDOMItem(data);
break;
case 1:
if (data.status !== "Offline") {
createStreamerDOMItem(data);
}
break;
case 2:
if (data.status === "Offline") {
createStreamerDOMItem(data);
}
break;
default:
createStreamerDOMItem(data);
console.log("Default switch");
break;
}
}
function createStreamerDOMItem(streamData) {
var divStart = '<div class="streamer-container">';
var divEnd = '</div></div>';
var divStreamerItem = '<div class="streamer-item" align="center">' + '<a target="_blank" href="' + streamData.url +
'"><iframe src="https://player.twitch.tv/?channel='+ streamData.name +'\" frameborder="0" scrolling="no" height="350" width="100%" /></a>' +
'<p id="viewer-count"><font color="yellow">' + streamData.viewers + ' personne(s) sur ' +
'</font>' + streamData.name + '</p>'
+ '';
var final = divStart + divStreamerItem + divEnd;
$(final).appendTo(".live-channels-container");
}
function clearStreamerDOMItems() {
$("div").remove(".streamer-container");
}
HTML
<div>
<div class="navbar-container" >
</div>
<br>
<div class="live-channels-container">
</div>
<!-- END OF STREAMER BOXES-->
</div>
Now I want to get ( var tempStreamers = ) username from DATABASE.
You can get the tempStreamers by JSONP method which you need a new api to output the data.
Use setinterval to run you function every 2 seconds.Then you will get the newest data.

Trying to change parameters in JQuery plugin file

I have a JQuery plugin i am using as part of my project. The file is located in the root of my solution folder under a file called "jquery.tablePagination.js" I want to alter some of the parameters inside of the file without hard coding the data.
The script is as follows..
(function ($) {
$.fn.tablePagination = function (settings) {
var defaults = {
firstArrow: (new Image()).src = "./images/first.gif",
prevArrow: (new Image()).src = "./images/prev.gif",
lastArrow: (new Image()).src = "./images/last.gif",
nextArrow: (new Image()).src = "./images/next.gif",
rowsPerPage: 5,
currPage: 1,
optionsForRows: [5, 10],
ignoreRows: []
};
settings = $.extend(defaults, settings);
return this.each(function () {
var table = $(this)[0];
var totalPagesId = '#' + table.id + '+#tablePagination #tablePagination_totalPages';
var currPageId = '#' + table.id + '+#tablePagination #tablePagination_currPage';
var rowsPerPageId = '#' + table.id + '+#tablePagination #tablePagination_rowsPerPage';
var firstPageId = '#' + table.id + '+#tablePagination #tablePagination_firstPage';
var prevPageId = '#' + table.id + '+#tablePagination #tablePagination_prevPage';
var nextPageId = '#' + table.id + '+#tablePagination #tablePagination_nextPage';
var lastPageId = '#' + table.id + '+#tablePagination #tablePagination_lastPage';
var possibleTableRows = $.makeArray($('tbody tr', table));
var tableRows = $.grep(possibleTableRows, function (value, index) {
return ($.inArray(value, defaults.ignoreRows) == -1);
}, false)
var numRows = tableRows.length
var totalPages = resetTotalPages();
var currPageNumber = (defaults.currPage > totalPages) ? 1 : defaults.currPage;
if ($.inArray(defaults.rowsPerPage, defaults.optionsForRows) == -1)
defaults.optionsForRows.push(defaults.rowsPerPage);
function hideOtherPages(pageNum) {
if (pageNum == 0 || pageNum > totalPages)
return;
var startIndex = (pageNum - 1) * defaults.rowsPerPage;
var endIndex = (startIndex + defaults.rowsPerPage - 1);
$(tableRows).show();
for (var i = 0; i < tableRows.length; i++) {
if (i < startIndex || i > endIndex) {
$(tableRows[i]).hide()
}
}
}
function resetTotalPages() {
var preTotalPages = Math.round(numRows / defaults.rowsPerPage);
var totalPages = (preTotalPages * defaults.rowsPerPage < numRows) ? preTotalPages + 1 : preTotalPages;
if ($(totalPagesId).length > 0)
$(totalPagesId).html(totalPages);
return totalPages;
}
function resetCurrentPage(currPageNum) {
if (currPageNum < 1 || currPageNum > totalPages)
return;
currPageNumber = currPageNum;
hideOtherPages(currPageNumber);
$(currPageId).val(currPageNumber)
}
function resetPerPageValues() {
var isRowsPerPageMatched = false;
var optsPerPage = defaults.optionsForRows;
optsPerPage.sort();
var perPageDropdown = $(rowsPerPageId)[0];
perPageDropdown.length = 0;
for (var i = 0; i < optsPerPage.length; i++) {
if (optsPerPage[i] == defaults.rowsPerPage) {
perPageDropdown.options[i] = new Option(optsPerPage[i], optsPerPage[i], true, true);
isRowsPerPageMatched = true;
}
else {
perPageDropdown.options[i] = new Option(optsPerPage[i], optsPerPage[i]);
}
}
if (!isRowsPerPageMatched) {
defaults.optionsForRows == optsPerPage[0];
}
}
function createPaginationElements() {
var htmlBuffer = [];
htmlBuffer.push("<div id='tablePagination'>");
htmlBuffer.push("<span id='tablePagination_perPage'>");
htmlBuffer.push("<select id='tablePagination_rowsPerPage'><option value='5'>5</option></select>");
htmlBuffer.push("per page");
htmlBuffer.push("</span>");
htmlBuffer.push("<span id='tablePagination_paginater'>");
htmlBuffer.push("<img id='tablePagination_firstPage' src='" + defaults.firstArrow + "'>");
htmlBuffer.push("<img id='tablePagination_prevPage' src='" + defaults.prevArrow + "'>");
htmlBuffer.push("Page");
htmlBuffer.push("<input id='tablePagination_currPage' type='input' value='" + currPageNumber + "' size='1'>");
htmlBuffer.push("of <span id='tablePagination_totalPages'>" + totalPages + "</span>");
htmlBuffer.push("<img id='tablePagination_nextPage' src='" + defaults.nextArrow + "'>");
htmlBuffer.push("<img id='tablePagination_lastPage' src='" + defaults.lastArrow + "'>");
htmlBuffer.push("</span>");
htmlBuffer.push("</div>");
return htmlBuffer.join("").toString();
}
if ($(totalPagesId).length == 0) {
$(this).after(createPaginationElements());
}
else {
$('#tablePagination_currPage').val(currPageNumber);
}
resetPerPageValues();
hideOtherPages(currPageNumber);
$(firstPageId).bind('click', function (e) {
resetCurrentPage(1)
});
$(prevPageId).bind('click', function (e) {
resetCurrentPage(currPageNumber - 1)
});
$(nextPageId).bind('click', function (e) {
resetCurrentPage(currPageNumber + 1)
});
$(lastPageId).bind('click', function (e) {
resetCurrentPage(totalPages)
});
$(currPageId).bind('change', function (e) {
resetCurrentPage(this.value)
});
$(rowsPerPageId).bind('change', function (e) {
defaults.rowsPerPage = parseInt(this.value, 10);
totalPages = resetTotalPages();
resetCurrentPage(1)
});
})
};
})(jQuery);
I want to be able to alter the following settings: RowsPerPage and OptionforRows.
I have tried to copy and paste the code from the script directly into my .aspx file next to some other Jquery/JavaScript I already have however the plugin doesn't run when I do this.
Could it be possible to write to the settings part of the file from the code behind? It would also work if the file could read the settings from a certain hidden field but I can't get it to run on my .aspx to do this. I'm not sure how to go about solving this issue.
I have ended up solving this issue by first copying the script and pasting in my .aspx file. I was originally copying the code inside of the document ready function:
$(document).ready(function)
Once I have had this done It was quite easy to pass through a variable from the code behind to be used as the required setting.
rowsPerPage: <%=PageRowAmount%>,
For the code behind I have added the following:
Public PageRowAmount As Integer = 10
and in the page_load I have added
Page.DataBind()
Solved!

Javascript error after upgrade to Drupal 7

I posted a similar question at the Drupal Forum, but I haven't had much luck.
I'm upgrading a site from D6 to D7. So far it's gone well, but I'm getting a Javascript error that I just can't pin down a solution for.
This is a cut down version of the whole script:
(function($) {
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
Date.prototype.toISODate =
new Function("with (this)\nreturn " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
The part that keeps throwing an error I'm seeing in Firebug is at:
Date.prototype.toISODate =
new Function("with (this)\n return " +
"getFullYear()+'-'+addZero(getMonth()+1)+'-'" +
"+addZero(getDate())+'T'+addZero(getHours())+':'" +
"+addZero(getMinutes())+':'+addZero(getSeconds())+'.000Z'");
Firebug keeps stopping at "addZero is not defined". JS has never been my strong point, and I know some changes have been made in D7. I've already wrapped the entire script in "(function($) { }(jQuery));", but I must be missing something else. The same script works perfectly on the D6 site.
Here is the "fixed" version of the whole code with #Pointy suggestion added. All I left out is the part of the script for making the hash that goes to Amazon, and some of my declared variables.
(function($) {
var typedText;
var strSearch = /asin:/;
var srchASIN;
$(document).ready(function() {
$("#edit-field-game-title-und-0-asin").change(function() {
typedText = $("#edit-field-game-title-und-0-asin").val();
$.ajax({
type: 'POST',
data: {typedText: typedText},
dataType: 'text',
url: '/asin/autocomplete/',
success:function(){
document.getElementById('asin-lookup').style.display='none';
x = typedText.search(strSearch);
y = (x+5);
srchASIN = typedText.substr(y,10)
amazonSearch();
}
});
});
$("#search_asin").click(function() {
$("#edit-field-game-title-und-0-asin").val('');
document.getElementById('name-lookup').style.display='none';
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#edit-body").val('');
srchASIN = $("#field-asin-enter").val();
amazonSearch();
});
$("#clear_search").click(function() {
$("#field-asin-enter").val('');
$("#edit-field-game-title-und-0-asin").val('');
$("#edit-title").val('');
$("#edit-field-subtitle-und-0-value").val('');
$("#edit-field-game-edition-und-0-value").val('');
$("#edit-field-release-date-und-0-value-date").val('');
$("#edit-field-release-dt2-und-0-value-date").val('');
$("#edit-field-asin-und-0-asin").val('');
$("#edit-field-ean-und-0-value").val('');
$("#edit-field-amazon-results-und-0-value").val('');
$("#field-amazon-platform").val('');
$("#field-amazon-esrb").val('');
$("#edit-body-und-0-value").val('');
document.getElementById('asin-lookup').style.display='';
document.getElementById('name-lookup').style.display='';
});
function amazonSearch(){
var ASIN = srchASIN;
var azScr = cel("script");
azScr.setAttribute("type", "text/javascript");
var requestUrl = invokeRequest(ASIN);
azScr.setAttribute("src", requestUrl);
document.getElementsByTagName("head").item(0).appendChild(azScr);
}
});
var amzJSONCallback = function(tmpData){
if(tmpData.Item){
var tmpItem = tmpData.Item;
}
$("#edit-title").val(tmpItem.title);
$("#edit-field-game-edition-und-0-value").val(tmpItem.edition);
$("#edit-field-release-date-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-release-dt2-und-0-value-date").val(tmpItem.relesdate);
$("#edit-field-asin-und-0-asin").val(tmpItem.asin);
$("#edit-field-ean-und-0-value").val(tmpItem.ean);
$("#field-amazon-platform").val(tmpItem.platform);
$("#field-amazon-publisher").val(tmpItem.publisher);
$("#field-amazon-esrb").val(tmpItem.esrb);
};
function ctn(x){ return document.createTextNode(x); }
function cel(x){ return document.createElement(x); }
function addEvent(obj,type,fn){
if (obj.addEventListener){obj.addEventListener(type,fn,false);}
else if (obj.attachEvent){obj["e"+type+fn]=fn; obj.attachEvent("on"+type,function(){obj["e"+type+fn]();});}
}
var styleXSL = "http://www.tlthost.net/sites/vglAmazonAsin.xsl";
function invokeRequest(ASIN) {
cleanASIN = ASIN.replace(/[-' ']/g,'');
var unsignedUrl = "http://xml-us.amznxslt.com/onca/xml?Service=AWSECommerceService&AssociateTag=theliterarytimes&IdType=ASIN&ItemId="+cleanASIN+"&Operation=ItemLookup&ResponseGroup=Medium,ItemAttributes,OfferFull&Style="+styleXSL+"&ContentType=text/javascript&CallBack=amzJSONCallback";
var lines = unsignedUrl.split("\n");
unsignedUrl = "";
for (var i in lines) { unsignedUrl += lines[i]; }
// find host and query portions
var urlregex = new RegExp("^http:\\/\\/(.*)\\/onca\\/xml\\?(.*)$");
var matches = urlregex.exec(unsignedUrl);
var host = matches[1].toLowerCase();
var query = matches[2];
// split the query into its constituent parts
var pairs = query.split("&");
// remove signature if already there
// remove access key id if already present
// and replace with the one user provided above
// add timestamp if not already present
pairs = cleanupRequest(pairs);
// encode the name and value in each pair
pairs = encodeNameValuePairs(pairs);
// sort them and put them back together to get the canonical query string
pairs.sort();
var canonicalQuery = pairs.join("&");
var stringToSign = "GET\n" + host + "\n/onca/xml\n" + canonicalQuery;
// calculate the signature
//var secret = getSecretAccessKey();
var signature = sign(secret, stringToSign);
// assemble the signed url
var signedUrl = "http://" + host + "/onca/xml?" + canonicalQuery + "&Signature=" + signature;
//document.write ("<html><body><pre>REQUEST: "+signedUrl+"</pre></body></html>");
return signedUrl;
}
function encodeNameValuePairs(pairs) {
for (var i = 0; i < pairs.length; i++) {
var name = "";
var value = "";
var pair = pairs[i];
var index = pair.indexOf("=");
// take care of special cases like "&foo&", "&foo=&" and "&=foo&"
if (index == -1) {
name = pair;
} else if (index == 0) {
value = pair;
} else {
name = pair.substring(0, index);
if (index < pair.length - 1) {
value = pair.substring(index + 1);
}
}
// decode and encode to make sure we undo any incorrect encoding
name = encodeURIComponent(decodeURIComponent(name));
value = value.replace(/\+/g, "%20");
value = encodeURIComponent(decodeURIComponent(value));
pairs[i] = name + "=" + value;
}
return pairs;
}
function cleanupRequest(pairs) {
var haveTimestamp = false;
var haveAwsId = false;
var nPairs = pairs.length;
var i = 0;
while (i < nPairs) {
var p = pairs[i];
if (p.search(/^Timestamp=/) != -1) {
haveTimestamp = true;
} else if (p.search(/^(AWSAccessKeyId|SubscriptionId)=/) != -1) {
pairs.splice(i, 1, "AWSAccessKeyId=" + accessKeyId);
haveAwsId = true;
} else if (p.search(/^Signature=/) != -1) {
pairs.splice(i, 1);
i--;
nPairs--;
}
i++;
}
if (!haveTimestamp) {
pairs.push("Timestamp=" + getNowTimeStamp());
}
if (!haveAwsId) {
pairs.push("AWSAccessKeyId=" + accessKeyId);
}
return pairs;
}
function sign(secret, message) {
var messageBytes = str2binb(message);
var secretBytes = str2binb(secret);
if (secretBytes.length > 16) {
secretBytes = core_sha256(secretBytes, secret.length * chrsz);
}
var ipad = Array(16), opad = Array(16);
for (var i = 0; i < 16; i++) {
ipad[i] = secretBytes[i] ^ 0x36363636;
opad[i] = secretBytes[i] ^ 0x5C5C5C5C;
}
var imsg = ipad.concat(messageBytes);
var ihash = core_sha256(imsg, 512 + message.length * chrsz);
var omsg = opad.concat(ihash);
var ohash = core_sha256(omsg, 512 + 256);
var b64hash = binb2b64(ohash);
var urlhash = encodeURIComponent(b64hash);
return urlhash;
}
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
function getNowTimeStamp() {
var time = new Date();
var gmtTime = new Date(time.getTime() + (time.getTimezoneOffset() * 60000));
return gmtTime.toISODate() ;
}
}(jQuery));
Here's a better version of your code:
Date.prototype.toISODate = function() {
function addZero(n) {
return ( n < 0 || n > 9 ? "" : "0" ) + n;
}
var d = this;
return d.getFullYear() + '-' +
addZero(d.getMonth() + 1) + '-' +
addZero(d.getDate()) + 'T' +
addZero(d.getHours()) + ':' +
addZero(d.getMinutes()) + ':' +
addZero(d.getSeconds()) + '.000Z';
};
That moves "addDate" inside the extension function, and it avoids the horrid with statement.

Categories