This Week's Projected Earnings

Adds a projected earnings for the previous week to dashboard.

目前为 2014-09-01 提交的版本。查看 最新版本

// ==UserScript==
// @name           This Week's Projected Earnings
// @description    Adds a projected earnings for the previous week to dashboard.
// @author         Tjololo12
// @version        0.2
// @include        https://www.mturk.com/mturk/dashboard
// @grant          GM_getValue
// @grant          GM_setValue
// @grant	       GM_deleteValue
// @namespace https://greasyfork.org/users/710
// ==/UserScript==

var TodaysEarnings = 0;
var NumberOfPages = 0;
//var todays_values = get_todays_data();
var todayDate = new Date();
var todayDay = todayDate.getDay();
var thisMonth = todayDate.getMonth();
var thisDay = todayDate.getDate();
var thisYear = todayDate.getFullYear();
var todayString = (thisMonth+1).toString()+thisDay.toString()+thisYear.toString();
var dayOfWeek = todayDate.getDay();
var lastDayOfLastMonth = new Date(thisYear, thisMonth, 0).getDate();
console.log(todayString + " " + todayDate + " " + lastDayOfLastMonth);
if (GM_getValue("weekly_hits"))
    var numHits = GM_getValue("weekly_hits");
else
    var numHits = 0;
if (GM_getValue("weekly_earnings"))
    TodaysEarnings = GM_getValue("weekly_earnings");

//if(todays_values.length != 0)
function update()
{
    today_row = get_todays_data();
    var go = true;
    if (today_row.length > 0)
    {
        if (GM_getValue("day_hits"))
            dayHits = GM_getValue("day_hits");
        var inner = today_row[1].innerHTML;
        inner = inner.split(">")[1];
        inner = inner.split("<")[0];
        console.log("inner: "+inner);
        if (dayHits == inner)
            go = false;
    }
    var daycounter = thisDay - (thisDay - dayOfWeek);
    console.log("daycounter: "+daycounter+" day: "+thisDay);
    if (daycounter < 0) //We need to figure out what the last day of the last month is to start there.
    {
        if (thisMonth - 1 < 0){
            thisYear -= 1;
            thisMonth = 11;
        }
        
        //daycounter = thisDay;
        for (var i = 0; i < dayOfWeek; i++){
            if (thisDay - 1 == 0)
                thisDay = lastDayOfLastMonth;
            daycounter += 1;
            thisDay -= 1;
        }
    }
    else
        thisDay -= daycounter;
    while (daycounter >= 0 && go)
    {
        console.log(daycounter+" "+thisDay);
        var done = false;
        var counter = 1;
        month = thisMonth+1;
        if (month <= 9)
            month = "0"+month.toString();
        var lastDayOfMonth = new Date(thisYear, thisMonth, 0).getDate();
        var dateToSearch = month.toString()+thisDay.toString()+thisYear.toString();
        while (!done)
        {     
            console.log("Processing page "+counter+" for date "+dateToSearch);
            detailed_status_page_link = "https://www.mturk.com/mturk/statusdetail?sortType=All&pageNumber=" + counter + "&encodedDate=" + dateToSearch;            
            console.log(detailed_status_page_link);
            counter += 1;
            var total = process_page(detailed_status_page_link);
            if (total[0] > 0){
                TodaysEarnings += total[0]; 
                numHits += total[1];
                if (thisDay == new Date().getDate())
                    //alert("Day Hits: "+total[1]);
                    GM_setValue("day_hits",total[1]);
            }
            else
                done = true;
        }
        if (thisDay + 1 > lastDayOfLastMonth)
        {
            thisDay = 1;
            if (thisMonth + 1 > 12)
            {
                thisMonth = 0;
                thisYear += 1;
            }
            else
                thisMonth += 1;
        }
        else
            thisDay += 1;
        daycounter -= 1;
    }
    //alert("Weekly earnings "+TodaysEarnings);
    //alert("Weekly Hits "+numHits);
    GM_setValue("weekly_earnings",TodaysEarnings);
    GM_setValue("weekly_hits",numHits);
    document.getElementById("ProjectedEarningsAmount").innerHTML = "$" + TodaysEarnings.toFixed(2);
}

function clear()
{
    if (confirm("Are you sure you want to clear everything from the weekly earnings script?")){
        GM_deleteValue("weekly_earnings");
        GM_deleteValue("weekly_hits");
        GM_deleteValue("day_hits");
        document.getElementById("ProjectedEarningsAmount").innerHTML = "$0.00";
    }
}

function showMetrics()
{
    var earningsPer = "$"+(parseInt(TodaysEarnings.toFixed(2))/parseInt(GM_getValue("weekly_hits"))).toFixed(2);
    console.log(earningsPer);
    var alertText = "Here's some random metrics!\nEarnings for last week: $"+TodaysEarnings.toFixed(2)+"\nNumber of hits completed: "+GM_getValue("weekly_hits")+"\nAverage earnings/hit: "+earningsPer+"\nI plan to add more metrics as I get requests for them!";
    alert(alertText);
}

//
// Insert the Projected Earnings in the dashboard.
// Copied from current_earnings script - Copyright (c) 2008, Mr. Berserk
// 
// Modified to suit
//

var allTds, thisTd;
allTds = document.getElementsByTagName('td');
for (var i = 0; i < allTds.length; i++)
{
    thisTd = allTds[i];
    if ( thisTd.innerHTML.match(/Total Earnings/) && thisTd.className.match(/metrics\-table\-first\-value/) )
    {
        var row = document.createElement('tr');
        row.className = "even";
        
        
        var projectedEarningsLink = document.createElement('a');
        projectedEarningsLink.innerHTML = "Week's Projected Earnings    ";
        projectedEarningsLink.title = "Click me for some nifty metrics!";

        projectedEarningsButton = document.createElement('button'); 
        projectedEarningsClearButton = document.createElement('button');
        
        projectedEarningsButton.textContent = 'U';
        projectedEarningsButton.title = 'Update weekly earnings';

        projectedEarningsButton.style.height = '14px';
        projectedEarningsButton.style.width = '10px';
        projectedEarningsButton.style.fontSize = '8px';
        projectedEarningsButton.style.border = '1px solid';
        projectedEarningsButton.style.padding = '0px';
        projectedEarningsButton.style.backgroundColor = 'transparent';
        
        projectedEarningsClearButton.textContent = 'X';
        projectedEarningsClearButton.title = 'Clear all storage';

        projectedEarningsClearButton.style.height = '14px';
        projectedEarningsClearButton.style.width = '10px';
        projectedEarningsClearButton.style.fontSize = '8px';
        projectedEarningsClearButton.style.border = '1px solid';
        projectedEarningsClearButton.style.padding = '0px';
        projectedEarningsClearButton.style.backgroundColor = 'transparent';
        
        projectedEarningsButton.addEventListener('click',update,false);
        projectedEarningsClearButton.addEventListener('click',clear,false);
        projectedEarningsLink.addEventListener('click',showMetrics,false);
        
        var cellLeft = document.createElement('td');
        cellLeft.className = "metrics-table-first-value";
        cellLeft.appendChild(projectedEarningsLink);
        cellLeft.appendChild(projectedEarningsButton);
        cellLeft.appendChild(projectedEarningsClearButton);
        row.appendChild(cellLeft);
        
        var cellRight = document.createElement('td');      
        cellRight.id="ProjectedEarningsAmount";
        cellRight.innerHTML = "$" + TodaysEarnings.toFixed(2);
        row.appendChild(cellRight);
        
        thisTd.parentNode.parentNode.insertBefore(row,thisTd.parentNode.nextSibling);
    }
}

//
// Functions
//

function get_todays_data()
{
    var tables = document.getElementsByClassName('metrics-table');
    for (var m = 0; m < tables.length; m++)
    {
        var table_rows = tables[m].getElementsByTagName('tr');
        if (table_rows[0][0] != "Date")
            continue;
        for (var n = 0; n < table_rows.length; n++)
        {
            var table_data = table_rows[n].getElementsByTagName('td');
            status_link = table_rows[n].getElementsByTagName('a');
            if(status_link[0])
            {
                if(table_data[0].innerHTML.match('Today'))
                {
                    console.log(table_data);
                    return table_data;
                }
            }
        }
    }
    return [];  // If no Today found we have to return something else it dies silently
}

//
// Process a detailed status page by added up the value of all the hits
//

function process_page(link)
{
    // use XMLHttpRequest to fetch the entire page, use async mode for now because I understand it
    var page = getHTTPObject();
    page.open("GET",link,false);      
    page.send(null);
    return earnings_subtotal(page.responseText); 
}


//
// Add up all the hit values on this detailed status page
// For the code to work we have to turn the responseText back
// into a DOM object so we can get the values using the 
// getElementsByClassName function. We use the create div trick.
//
// Modified to not add in those hits that have already been rejected
//

function earnings_subtotal(page_text)
{
    var sub_total= 0;
    var index = 0;
    var page_html = document.createElement('div');
    page_html.innerHTML = page_text;
    
    var amounts = page_html.getElementsByClassName('statusdetailAmountColumnValue');
    var statuses = page_html.getElementsByClassName('statusdetailStatusColumnValue');
    
    if (amounts.length == 0)
        return sub_total;
    for(var k = 0; k < amounts.length; k++)
    {
        if(statuses[k].innerHTML != 'Rejected')
        {
            index = amounts[k].innerHTML.indexOf('$');
            sub_total = sub_total + parseFloat(amounts[k].innerHTML.substring(index+1));
        }
    }
    return [sub_total,amounts.length];
}


//
// XMLHttpRequest wrapper from web
//

function getHTTPObject()  
{ 
    if (typeof XMLHttpRequest != 'undefined')
    { 
        return new XMLHttpRequest();
    }
    try
    { 
        return new ActiveXObject("Msxml2.XMLHTTP");
    } 
    catch (e) 
    { 
        try
        { 
            return new ActiveXObject("Microsoft.XMLHTTP"); 
        } 
        catch (e) {} 
    } 
    return false;
}


//
//  Cookie functions copied from http://www.w3schools.com/JS/js_cookies.asp
//

function setCookie(c_name,value,exdays)
{
    var exdate=new Date(); 
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}


function getCookie(c_name)
{
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++)
    {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name)
        {
            return unescape(y);
        }
    }
}

function clearCookies()
{
    setCookie("MturkSubtotal",0,1);
    return true;
}