Все о фотобанках и микростоках, купить и продать фото, работа для фотографа и иллюстратора


Ответ Правила нашего форума>
 
Опции темы Поиск в этой теме Опции просмотра
Старый 04.12.2016, 02:26   #21
Новичок
 
Регистрация: 29.10.2012
Сообщения: 104
Репутация: 46
Оставлено благодарностей: 30
Получено благодарностей: 51
По умолчанию Re: User Scripts для Шаттерстока

Не жалко конечно, тем более что первые два из открытых источников:
1) https://gist.github.com/deymosD - это ShowImageInfo и ShowDownloadLocations.

2) Это для показа дневной статистики продажи вектора и растра, отметка растра, плюс переменной newfrom можно задать индекс картинки для разделения на новый и старый контент. Писалось для себя и под свои нужды, плюс первая попытка написания скриптов со слабым знанием яваскрипт, по стилю конечно "гавнокод", но работает. Проверено только на связке chrome+tampermonkey.
PHP код:
// ==UserScript== 
// @name        DailyCalc 
// @namespace   Ukraine
// @version     1.0 
// @description Сalc for vectors and photos 
// @author      ToBad 
// @match       http://submit.shutterstock.com/stats_date.mhtml* 
// @grant       none 
// ==/UserScript== 

(function() {

    var 
newfrom 0;

    function 
addGlobalStyle(css) {
        var 
headstyle;
        
head document.getElementsByTagName('head')[0];
        if (!
head) return;
        
style document.createElement('style');
        
style.type 'text/css';
        
style.innerHTML css;
        
head.appendChild(style);
    }
    
addGlobalStyle(".x{position:relative;width:140px;overflow:hidden}.y:after{content:'PHOTO';background:#282;z-index:800;padding-top:2px;color:#fff;font-family:Roboto;letter-spacing:1px;font-weight:400;text-transform:none;text-align:center;display:inline-block;" +
        
"width:110px;font-size:10px;line-height:14px;-webkit-transform-origin:center center;-ms-transform-origin:center center;transform-origin:center center;top:8px;border-bottom:2px solid #006400;right:-38px;-webkit-transform:rotate(45deg);-ms-transform:rotate(45deg);transform:rotate(45deg);position:absolute}");
    var 
oldpic 0,
        
newpic 0,
        
vect 0,
        
rastr 0,
        
curamm 0,
        
oldamm 0,
        
newamm 0,
        
vecamm 0,
        
rasamm 0,
        
fl 0;
    var 
document.getElementsByTagName('table');
    for (var 
0t.lengthi++) {
        var 
t[i].getElementsByTagName('tr')[0].getElementsByTagName('td')[0].innerHTML;
        if ((
s.length 0) && (s[0] + s[s.length 1] === '[]')) {
            
tr t[i].getElementsByTagName('tr');
            if (
fl === 0fl i;
            for (var 
0tr.lengthn++) {
                
td tr[n].getElementsByTagName('td');
                if (((
td.length === 5) || (td.length === 9)) && (tr[n].innerHTML.indexOf('thumb_small') > 0)) {
                    if (
td.length === 5cnt 1;
                    else 
cnt 2;
                    for (var 
0cntz++) {
                        var 
pics Number(td[(5) + 2].innerHTML);
                        if (
td[(5) + 3].innerHTML.substr(01) === '$'curamm Number(td[(5) + 3].innerHTML.substr(1));
                        else 
curamm 0;
                        var 
tit td[(5) + 1].getElementsByTagName('img')[0].title;
                        if (
tit.indexOf(' - stock vector') > 0) {
                            
vect vect pics;
                            
vecamm vecamm curamm;
                        } else if (
tit.indexOf(' - stock photo') > 0) {
                            
rastr rastr pics;
                            
rasamm rasamm curamm;
                            
td[(5) + 1].innerHTML td[(5) + 1].innerHTML.replace('thumb_image_container"''thumb_image_container x y"');
                        }
                        if (
Number(td[(5) + 0].getElementsByTagName('a')[0].innerHTML) >= newfrom) {
                            
newpic newpic pics;
                            
newamm newamm curamm;
                        } else {
                            
oldpic oldpic pics;
                            
oldamm oldamm curamm;
                        }
                    }
                }
            }
        }
    }
    var 
stat '[ ' vect.toString() + ' vector=$' vecamm.toFixed(2).toString() + ', ' rastr.toString() + ' photo=$' rasamm.toFixed(2).toString();
    var 
sp ' '.repeat(14);
    if (
oldpic 0stat stat ' ]' sp '[ ' oldpic.toString() + ' old=$' oldamm.toFixed(2).toString() + ', ' newpic.toString() + ' new=$' newamm.toFixed(2).toString() + ' ]' sp;
    else 
stat stat ' ]' sp '[ ' newpic.toString() + ' summary=$' newamm.toFixed(2).toString() + ' ]' sp;
    if (
fl 0) {
        var 
fix t[fl].getElementsByTagName('tr')[0].getElementsByTagName('td')[0];
        
stat stat fix.innerHTML;
        
fix.innerHTML stat;
    }
})(); 

Что касается удаления батчей целиком - ещё не закончено.
ToBad вне форума   Ответить с цитированием
Старый 04.12.2016, 11:31   #22
Заблокирован(а) перманентно
 
Регистрация: 23.04.2011
Сообщения: 1,568
Репутация: 911
Оставлено благодарностей: 1,302
Получено благодарностей: 970
По умолчанию Re: User Scripts для Шаттерстока

ссылки на скрипты битые
ratamaque вне форума   Ответить с цитированием
Старый 04.12.2016, 11:39   #23
Старожил
 
Аватар для Yingko
 
Регистрация: 03.08.2009
Адрес: Россия
Сообщения: 713
Репутация: 866
Оставлено благодарностей: 509
Получено благодарностей: 868
По умолчанию Re: User Scripts для Шаттерстока

Цитата:
Сообщение от ratamaque
ссылки на скрипты битые
github ? у меня открывается
Yingko вне форума   Ответить с цитированием
Старый 04.12.2016, 11:41   #24
Заблокирован(а) перманентно
 
Регистрация: 23.04.2011
Сообщения: 1,568
Репутация: 911
Оставлено благодарностей: 1,302
Получено благодарностей: 970
По умолчанию Re: User Scripts для Шаттерстока

Цитата:
Сообщение от Yingko
github ? у меня открывается
у меня открывается какой-то рекламный мусор, c fenki.net

Последний раз редактировалось ratamaque, 04.12.2016 в 12:12.
ratamaque вне форума   Ответить с цитированием
За это сообщение сказал спасибо:
runedance (23.01.2017)
Старый 04.12.2016, 11:53   #25
Новичок
 
Регистрация: 03.09.2016
Сообщения: 199
Репутация: 370
Оставлено благодарностей: 1,311
Получено благодарностей: 362
По умолчанию Re: User Scripts для Шаттерстока

народ, вы не боитесь ставить неизвестно что себе на шаттер?
VickyS сейчас на форуме   Ответить с цитированием
Старый 04.12.2016, 12:26   #26
Старожил
 
Регистрация: 07.06.2016
Сообщения: 759
Репутация: 970
Оставлено благодарностей: 1,207
Получено благодарностей: 971
По умолчанию Re: User Scripts для Шаттерстока

Цитата:
Сообщение от ToBad
2) Это для показа дневной статистики продажи вектора и растра
Как выглядит результат работы скрипта? Можно скриншот?
tumoxasan вне форума   Ответить с цитированием
Старый 04.12.2016, 15:07   #27
Новичок
 
Регистрация: 29.10.2012
Сообщения: 104
Репутация: 46
Оставлено благодарностей: 30
Получено благодарностей: 51
По умолчанию Re: User Scripts для Шаттерстока

Цитата:
Сообщение от tumoxasan
Как выглядит результат работы скрипта? Можно скриншот?

Да, можно, только портфель не мой и заскриншотить разрешили только при условии полной анонимности. Не думал, что стокеры настолько суеверные....

Итак, на первом скриншоте в середине результат работы моего скрипта (по дневной статистике без разделения на новый или старый контент), календарь слева и инфо справа это работа ShowImageInfo по ссылке с github. Скриншот 2 - панель слева это второй скрипт с github под названием ShowDownloadLocations. Ну и на последнем мой скрипт по удалению батчей который сейчас тестирую. Хотя по последнему скриншоту трудно понять его работу...
Изображения
Тип файла: jpg uscript1.jpg (120.7 Кбайт, 96 просмотров)
Тип файла: jpg uscript2.jpg (109.2 Кбайт, 82 просмотров)
Тип файла: jpg uscript3.jpg (31.4 Кбайт, 58 просмотров)
ToBad вне форума   Ответить с цитированием
За это сообщение сказал спасибо:
Юрчелло (08.11.2017)
Старый 04.12.2016, 15:21   #28
Новичок
 
Регистрация: 29.10.2012
Сообщения: 104
Репутация: 46
Оставлено благодарностей: 30
Получено благодарностей: 51
По умолчанию Re: User Scripts для Шаттерстока

Цитата:
Сообщение от VickyS
народ, вы не боитесь ставить неизвестно что себе на шаттер?

Честно говоря подобный страх оправдан ибо доверяясь автору скрипта нужно быть уверенным ещё в том, что он сам относится к безопасности серьёзно. Возможности скриптов большие. Приведу пример, скрипт shutter places которым и я пользовался до того как нашёл аналог - конечно хороший и автор заслуживает на мой взгляд доверия, но то, что установлено на компьютере это только загрузчик основного скрипта который постоянно живёт на github автора. Разумеется это сделано для удобства, автор в любой момент внесёт изменения и они автоматически начнут работать у всех пользователей. Но что если кто-либо получит доступ к его аккаунту на github? Он встроит в скрипт вредоносный функционал и может запросто получить доступ а аккаунтам пользователей скрипта...
Я немного знаком с программированием по этому прежде чем установить что либо обязательно изучаю код, ну а остальным советую конечно же быть осторожными. В конце концов найдя что-то можно выложить и спросить совета не опасно ли использовать. Уверен, что тут есть много людей которые хорошо разбираются в javascript.
ToBad вне форума   Ответить с цитированием
За это сообщение сказали спасибо:
runedance (19.01.2017), VickyS (04.12.2016)
Старый 04.12.2016, 15:24   #29
Новичок
 
Регистрация: 29.10.2012
Сообщения: 104
Репутация: 46
Оставлено благодарностей: 30
Получено благодарностей: 51
По умолчанию Re: User Scripts для Шаттерстока

Цитата:
Сообщение от ratamaque
ссылки на скрипты битые

Тогда если никто не против - выложу это тут:

PHP код:
// ==UserScript==
// @name         Shutterstock.ShowImageInfo
// @namespace    
// @version      1.8.4
// @updateURL    https://gist.github.com/deymosD/ad6cc21b80f84eab4fbd/raw/f39df63fd8ff0b458afc93a1dc377404bb2a4f03/Shutterstock.ShowImageInfo.user.js
// @description  Show detailed image info on Shutterstock's daily stats page. Based on Satinka's https://gist.github.com/satinka/5479a93d389a07d41246
// @author       GG
// @match        http://submit.shutterstock.com/stats_date.mhtml*
// @match        https://submit.shutterstock.com/stats_date.mhtml*
// @copyright    2016, Satinka, GG
// @require      https://code.jquery.com/jquery-latest.min.js
// @require      https://code.jquery.com/ui/1.11.4/jquery-ui.min.js
// @grant        none

// ==/UserScript==

// NEW: 
// v1.8 - added DatePicker, support for async call to get daily or montly stats, made all divs draggable
// v1.7 - moving popup div enabled

'use strict';
var 
$j jQuery.noConflict();

// =========== PARAMETERS ===========

var enableDatePicker true;  // if you don't need date picker, set this to false
var loadMonthyEarningsOnYMChange true// set to false to disable loading earnings page when month or year are changed in date picker

// ==/UserScript==

// in reverse image search, don't return results from stock sites (idea by mandritoiu); add other sites in the form --> +-site:.domain.com (sometimes Google ignores this):

var noStockSites "-site:dreamstime.com+-site:shutterstock.com+-site:shutterstock.in+-site:istockphoto.com+-site:fotolia.com+-site:123rf.com+-site:veer.com+-site:istockphoto.com"

// not sure why they q= and oq= are used, but here are both :D, can't hurt; i could do it much nicer, maybe in the future... :)
// Google Images sometimes ignores excludes and will serve content from SS or other excluded sites

var googleSearch "https://www.google.com/searchbyimage?q=" noStockSites "&oq=" noStockSites "&image_url=";

//===================================

var div;          
var 
opened 0;

// i use smoothness theme for the datepicker and here we load external CSS 

if (enableDatePicker) {
    var 
link window.document.createElement('link');
    
link.rel 'stylesheet';
    
link.type 'text/css';
    
link.href 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/smoothness/jquery-ui.css'// get smoothness CSS; check http://jqueryui.com/themeroller/ for others, just change the theme name in url
    
document.getElementsByTagName("HEAD")[0].appendChild(link);                                       // other themes: http://rtsinani.github.io/jquery-datepicker-skins/, have fun!
}

$j(document).ready(function() {
    
CreateStyles();    

    
div document.createElement('div');
    
div.className "gginfo";
    if (
localStorage.getItem("positionImageInfo")) { 
        var 
position $j.parseJSON(localStorage.getItem("positionImageInfo"));
        
div.style.top position.top "px";
        
div.style.left position.left "px";
    }

    
$j("div.shutterstock_submit_page").append(div);

    
$j("div.gginfo").draggable({
        
stop: function(eventui){
            
localStorage.setItem("positionImageInfo"JSON.stringify(ui.position));
        }
    });
    
$j("div.gginfo").hover( function() {$j(this).css("cursor""move");}, function(){ $j(this).css("cursor""default"); });
    
resetDivInfo();
    
fixLinksinDailyStats();

    (
enableDatePicker) && addDatePicker();

});

function 
addDatePicker() {
    
// wrap table element with div.ggHack because we're gonna need to import HTML content of different pages
    
$j("div.shutterstock_submit_page table:first").wrap("<div class='ggHack'></div>");

    
// get date from URL
    
var datepicker document.createElement('div');
    
datepicker.id "datepicker";
    if (
localStorage.getItem("positionDatePicker")) { 
        var 
position $j.parseJSON(localStorage.getItem("positionDatePicker"));
        
datepicker.style.top position.top "px";
        
datepicker.style.left position.left "px";
    }

    
$j("div.shutterstock_submit_page").append(datepicker);

    
$j("div#datepicker").draggable({
        
stop: function(eventui){
            
localStorage.setItem("positionDatePicker"JSON.stringify(ui.position));
        }
    });
    
$j("div#datepicker").hover( function() {$j(this).css("cursor""move");}, function(){ $j(this).css("cursor""default"); });

    
$j("div#datepicker").datepicker({   // check https://api.jqueryui.com/datepicker/ for API and play with options
        
maxDate"+0D",  // not much fun to go beyond today, no stats will be available
        
showOtherMonthstrue
        
changeMonthtrue,
        
changeYeartrue,
        
defaultDatewindow.location.href.match(/date=(\d\d\d\d\-\d\d\-\d\d)/)[1], // get the default date from the URL
        
dateFormat:"yy-mm-dd",
        
firstDay1,                // start with monday, set to 0 for sunday (but why!?)
        
showButtonPaneltrue,
        
currentText"This month",
        
yearRange:"2003:+0"// don't want to go to pre-Shutterstock times...
        
onSelect: function(selected,event) { 
            
updateTable(selected);  
            
$j("div.gginfo").show(); // when we select date, load stats for the date and show the image info div
        
}  
    });

    
// add this only if selected in params above
    
if (loadMonthyEarningsOnYMChange) {
        
$j("div#datepicker").datepicker("option""onChangeMonthYear", function (yearmonthi) {   // when we change month or year, load earnings for that month in that year
            
if (month 10month "0" month;
            var 
yearMonth year "-" month;
            var 
monthLink "http://submit.shutterstock.com/stats.mhtml?year_month=" yearMonth;
            
$j("<link/>", {
                
rel"stylesheet",
                
type"text/css",
                
href"/css/stats.css?rev=1"            // we need to add style for statistics table
            
}).appendTo("head"); 

            
$j("div.shutterstock_submit_page table:first").html("<h2>Loading...</h2>");
            
$j("div.shutterstock_submit_page center div").text(yearMonth);
            
$j("div.shutterstock_submit_page div.ggHack").load(monthLink " div.shutterstock_submit_page table#stats-table");
            
$j("div.gginfo").hide();
        });
    }   
}
function 
updateTable(date){
    var 
newLink "http://submit.shutterstock.com/stats_date.mhtml?date=" date;
    
$j("div.shutterstock_submit_page table:first").html("<h2>Loading...</h2>");
    
$j("div.shutterstock_submit_page center div").text(date);
    
$j("div.shutterstock_submit_page div.ggHack").load(newLink " div.shutterstock_submit_page table:first", function() {
        
fixLinksinDailyStats(); // gotta do that cause we just reloaded content
    
});

}

function 
resetDivInfo(){
    
$j("div.gginfo").html("<b>Click on image ID to show image info.</b>");
    return;
}

function 
fixLinksinDailyStats(){

    
$j("a.link").each(function() {
        var 
ahref this.href.match(/.*www.*id=(\d*)$/);
        if (
ahref) {
            var 
href ahref[1];
            $(
this).removeAttribute("href");
            $(
this).on("click","a.link", function() { 
                if (
opened != href) {
                    
GetImageData(href);
                    
$j("div.gginfo").show();
                }
                
opened href// remember which image is still opened
            
} );
        }
    });
}


function 
GetImageData(imageID) {

    
div.innerHTML "<h4>Loading...</h4>";
    var 
= new Date();
    var 
d.getTimezoneOffset() / 60;

    
$j.ajax({
        
urlwindow.location.protocol '//submit.shutterstock.com/show_component.mhtml?component_path=mobile/comps/image_detail.mj&photo_id=' imageID,
        
type"get",
        
dataType"html",
        
cachetrue,
        
error: function (requeststatuserror) {
            
console.log(request.responseText);
        },
        
success: function( data ){
            var 
imageInfo $j.parseJSON(data);

            if (
imageInfo) {
                var 
downloads imageInfo.latest_downloads;
                var 
keywords imageInfo.keywords;
                var 
totals imageInfo.totals;
                var 
today totals.today;
                var 
all totals.all_time;
                var 
table;
                
div.innerHTML "<span class=\"closeInfo\">Close</span><br />";
                
div.innerHTML += "<h4>Image statistics</h4>";
                
div.innerHTML += "<a target=\"_new\" href=\"http://www.shutterstock.com/pic.mhtml?id=" imageID "\"><img align=\"right\" class=\"resize\" src=\"http:" imageInfo.thumb_url "\" /></a>";
                
div.innerHTML += "<h5> " imageInfo.description "</h5>";
                
div.innerHTML += "<b>Image ID:</b> <a target=\"_new\" href=\"http://www.shutterstock.com/pic.mhtml?id=" imageID "\">" imageID "</a><br />";

                var 
uploaded = new Date( ((imageInfo.uploaded_date/1000) + (6+n) * 3600)*1000).toDateString();
                var 
daysonline Math.round((new Date().getTime() - imageInfo.uploaded_date) / (1000 24 60 60));
                
div.innerHTML += "<b>Uploaded on</b> " uploaded  " (" daysonline " days ago)<br /><br />";


                
div.innerHTML += "Earned <b>" all.earnings "$</b>";
                if (
today.earnings 0) {
                    
div.innerHTML += " (<b>" today.earnings "$</b> today)";
                }
                
div.innerHTML += "<br />";
                var 
s1 = (today.downloads) != "s" "";
                var 
s2 = (all.downloads) != "s" "";

                
div.innerHTML += "Downloaded <b>" all.downloads " time" s2;
                if (
today.downloads 0) {
                    
div.innerHTML += " (<b>" today.downloads " time" s1 "</b> today)";
                }
                
div.innerHTML += "<br />";

                if (
all.downloads 0) {
                    var 
rpd = (all.earnings all.downloads).toFixed(2);
                    
div.innerHTML += "Return per download: <b>" rpd "$</b><br />";
                }
                var 
editURL "http://submit.shutterstock.com/edit_media.mhtml?type=photos&approved=1&id=" imageID;
                
div.innerHTML += "<a href=\"" editURL "\" target=\"_new\">Edit title and keywords</a> (opens new window)<br/>";

                
div.innerHTML += "<br /><a target=\"_new\" href =\"" googleSearch "http:" imageInfo.thumb_url "\">Find image in use via Google Images</a><br />";

                if (
keywords.length 0) {
                    
div.innerHTML += "<br /><b>Keywords used to download image:</b><br />";
                    
table "<table  width=\"200px\">";
                    
table += "<thead><th align=\"right\">Keyword</th><th align=\"right\">% used</th></thead><tbody>";
                    
keywords.forEach(function(kw) { 
                        
table += "<tr><td align=\"right\">" kw.keyword "</td><td align=\"right\">" parseFloat(kw.percentage).toFixed(2) + "</td></tr>";
                    });
                    
table += "</tbody></table>";
                    
div.innerHTML += table;
                }
                else {
                    
div.innerHTML += "<br /><b>No keyword info available.</b><br />";
                }

                if (
downloads.length 0) {
                    
div.innerHTML += "<br /><b>Latest downloads</b> (max 20 or max last 365 days):</b><br />";
                    
table "<table  width=\"300px\">";
                    
table += "<thead><th align=\"left\">Date</th><th align=\"right\">Earnings</th></thead><tbody>";
                    
downloads.forEach(function(arg) { 
                        var 
date = new Date ( ((arg.date_time/1000) + (6+n) * 3600)*1000).toUTCString().toLocaleString();
                        
table += "<tr><td align=\"left\">" date "</td><td align=\"right\">" arg.amount "</td></tr>";
                    });
                    
table += "</tbody></table><br /";
                    
div.innerHTML += table;
                }
                else
                {
                    
div.innerHTML += "<br /><b>No downloads in the last 365 days.</b><br />";
                }
            }

            
$j("span.closeInfo").on("click", function(){ 
                
//  $j("div.gginfo").hide();      // i'd rather keep the info on the screen than hide the div
                
resetDivInfo();
                
opened 0;
            });
        }
    });
}

// following code created by https://gist.github.com/satinka/5479a93d389a07d41246

function CreateStyles() {
    var 
sheet = (function() {
        var 
style document.createElement("style");
        
style.appendChild(document.createTextNode(""));
        
document.head.appendChild(style);
        return 
style.sheet;
    })(); 

    var 
resize "max-width: 30%; max-height:30%;";
    var 
alink "cursor: hand; cursor: pointer;";
    var 
closelink "cursor: hand; cursor: pointer; text-decoration: underline; ";
    var 
gginfo "position: fixed; top: 60px; right: 10px; border:4px solid #eeeeee;" +
        
"width: 330px; max-height: 70%;" 
        
"font-weight: normal;" +
        
"resize: both;" +
        
"padding: 10px 10px 10px 10px;" 
        
"background-color: white;" +
        
"opacity: 1;" +
        
"overflow: auto;" +
        
"font-size: 12px;";
    var 
datepick "position: fixed; top: 60px; left: 15px; font-size: 12px; width: 300px";

    
addCSSRule(sheet"div.gginfo"gginfo0);
    
addCSSRule(sheet"span.closeInfo"closelink0);
    
addCSSRule(sheet"a.link:hover"alink0);
    
addCSSRule(sheet"img.resize"resize0);
    
addCSSRule(sheet"div#datepicker a"alink0);  // make pointer when hovering over linkable elements
    
addCSSRule(sheet"div#datepicker"datepick0);
}


function 
addCSSRule(sheetselectorrulesindex) {
    if(
"insertRule" in sheet) {
        
sheet.insertRule(selector "{" rules "}"index);
    }
    else if(
"addRule" in sheet) {
        
sheet.addRule(selectorrulesindex);
    }


PHP код:
// ==UserScript==
// @name         Shutterstock.ShowDownloadLocations
// @namespace    
// @version      1.6.5
// @updateURL    https://gist.github.com/deymosD/e525474294ee40a44e54/raw/50fe846ee72e7f24dc9319d96661533bda1625ff/Shutterstock.ShowDownloadLocations.user.js
// @description  Show detailed localization to Shutterstock Latest Downloads map, based on Satinka's https://gist.github.com/satinka/5479a93d389a07d41246
// @author       Satinka, GG update
// @match        http://submit.shutterstock.com/home.mhtml*
// @match        https://submit.shutterstock.com/home.mhtml*
// @copyright    2016, Satinka
// @require      http://code.jquery.com/jquery-latest.min.js
// @require      https://code.jquery.com/ui/1.11.4/jquery-ui.min.js
// @require      https://raw.githubusercontent.com/sytelus/CryptoJS/master/rollups/md5.js 
// @grant        none

// ==/UserScript==
/* jshint -W097 */

// NEWS
// v1.6: hashes SS response for location and image earnings
//       enables dragging page elements and moving them around; stores positions across requests (to disable, remove div#* keys from localStorage or set makeOriginalDivsDraggable to false,  line #30
//       if trackMySales enabled, stores info about downloaded images in local storage; objective: create arrival rate distribution

'use strict';

var 
useShortCountryName false;       // US (true), or United States of America (false) - false is now default as it looks nicer :)
var googleMaps "https://www.google.com/maps/place/"
var 
displayEarnings true// set to false to disable display of earnings for last 7 days and today on top of popup
var displayRecentEarnings true// set to false to disable display of earnings for recent images 
var makeOriginalDivsDraggable true// makes content on front page draggable, you can move sections around (map, track your sets, graphs, content overview, profile, forum and blog


var debug false// easier for me during development
var trackMySales true// for future development, saves info on individual sales in local storage

//===================================


var $j jQuery.noConflict();
var 
div;

$j(document).ready(function() {
    
createStyles();   
    var 
containerDiv document.createElement('div');
    
containerDiv.id "dragContainer";
    
$j("div.shutterstock_submit_page").append(containerDiv);
    
    
div document.createElement('div');
    
div.id "ggDL";
    
$j("div#dragContainer").append(div);
    
    if (
localStorage.getItem("positionDownloadLocations")) { 
        var 
position $j.parseJSON(localStorage.getItem("positionDownloadLocations"));
        
$j("div#dragContainer").css({
            
topposition.top,
            
leftposition.left});
    } 
    
    
$j("div#dragContainer").draggable({
        
opacity0.9,
        
handle"div",
        
stop: function(eventui){
            
localStorage.setItem("positionDownloadLocations"JSON.stringify(ui.position));
        }
    });
    
$j("div#ggDL").hover( function() {$j(this).css("cursor""move");}, function(){ $j(this).css("cursor""default"); });

    
localStorage.removeItem('lastDownloads'); // remove cached locations response on page refresh
    
localStorage.removeItem('lastEarnings'); // remove cached locations response on page refresh,
    
localStorage.removeItem('lastSevenDays'); // remove cached locations response on page refresh

    
showLocations();

    (
makeOriginalDivsDraggable) && makeDivsDraggable();

    
window.setInterval(showLocations,60000); // refresh every 60 seconds
    
window.setInterval(retrieveEarnings,60000);
});


function 
makeDivsDraggable() {
    var 
divs = [ "div#download_map_column""div#track_your_sets""div#graph_column""div#content_overview_column""div#public_profile""div.content_container" ];

    
divs.forEach( function(entry) {
        
$j(entry).draggable({
            
stop: function(eventui){
                
localStorage.setItem(entryJSON.stringify(ui.position));
            }
        }); 
// to hide them, use .hide() instead of draggable()

        
if (localStorage.getItem(entry)) { 
            var 
position $j.parseJSON(localStorage.getItem(entry));
            
$j(entry).css('top'position.top "px");
            
$j(entry).css('left'position.left "px");
        }
    }
                );
}


function 
existsInLocalStorage(keydata) {
    var 
thisResponseHash CryptoJS.MD5(data).toString(CryptoJS.enc.Base64);
    if (
localStorage.getItem(key) == thisResponseHash) {
        if (
debug) { console.log("No change in " key ": " thisResponseHash); };
        return 
true;
    }
    else {
        
localStorage.setItem(keythisResponseHash);
        if (
debug) { console.log("Inserting into " key ": " thisResponseHash); }
        return 
false;
    }
}

function 
showLocations() {


    
$j.ajax({
        
urlwindow.location.protocol '//submit.shutterstock.com/show_component.mhtml?component_path=download_map/recent_downloads.mh',
        
type"get",
        
dataType"html",
        
error: function (requeststatuserror) {
            
//alert(request.responseText);
        
},
        
success: function( data ){
            if (
existsInLocalStorage('lastDownloads'data)) {
                
retrieveEarnings();
                
$j("div.refreshCoords").text("Refresh");
                return 
true;
            }

            var 
coords $j.parseJSON(data);
            
localStorage.removeItem('lastSevenDays'); 

            
div.innerHTML "<span class=\"refreshCoords\">Refresh</span>";

            if (
displayEarnings){
                
div.innerHTML += "<H4>Earnings</h4>";
                
retrieveLastWeekEarnings();
                
div.innerHTML += "Last 7 days: <span id=\"last7\"></span>$<br />";
                
div.innerHTML += "Today: <span id=\"today\"></span>$<br />";
                
//      div.innerHTML += "Lifetime: <span id=\"lifetime\"></span>$<br />";
                //      div.innerHTML += "Unpaid: <span id=\"unpaid\"></span>$<br />";
            
}

            
div.innerHTML += "<h4>Download locations</h4>";

            
$j.each(coords, function( indel ) {
                var 
id el.media_id;
                var 
img el.thumb_url;
                var 
time el.time;
                var 
loc;

                if (
el.latitude !== null && el.longitude !== null) {
                    
$j.ajax({
                        
url'https://maps.googleapis.com/maps/api/geocode/json?latlng=' el.latitude ',' el.longitude,
                        
type"get",
                        
dataType"html",
                        
error: function (requeststatuserror) {
                            
console.log(request.responseText);
                        },
                        
success: function( data ){
                            var 
res $j.parseJSON(data);
                            
// moramo ovako jer je asinkrono. dok u divu ispise tekst, ovo jos nije stiglo sa servera
                            
if (res.status == "OK") {
                                
$j("a.location" id "-" time).text(ExtractLocation(res.results[0].address_components));
                            } 
                            else {
                                
$j("a.location" id "-" time).text("Can't convert to location :\(");
                            }

                        }  
                    }); 

                }
                if (
trackMySales) {
                    
localStorage.setItem(id "-" timeJSON.stringify(el)); // save image info, key = (id-time_of_download);
                
}

                if (
debug) { console.log("Added " id "to local storage"); }

                
// if it's footage, need to change thumbnail size; too bad i can't test it with 1 footage a century
                
var footageWidth "";
                if (
el.media_type != "photo") {
                    
footageWidth "width=\"100px\" height=\"59\" ";
                }
                
div.innerHTML += "<a target=\"_new\" href=\"http://www.shutterstock.com/pic.mhtml?id=" id "\"><img " footageWidth "src=\"" img "\" /></a><br />";

                if (
el.latitude  && el.longitude ) {
                    
div.innerHTML +=  "<a class=\"location" id +  "-" +  time "\" target=\"_new\" href=\"" googleMaps el.latitude "+"el.longitude "\"></a><br />";
                }
                else {
                    
div.innerHTML += "Unknown, middle of Atlantic :)<br />";
                }

                var 
=  new Date().getTimezoneOffset() / 60// offset from GMT
                // taking only time from date - 6+n - NY time + offset from GMT gives local - works wine for me
                
var = new Date((time + (6+n) * 3600) *1000).toTimeString().split(" ")[0]; 
                if (
displayRecentEarnings) {
                    
div.innerHTML += "Earnings: <span id=\"earnings" id time "000\">N/A</span><br />";
                    if (
debug) {console.log(time)};
                }
                
div.innerHTML += "Time: " "<hr />";
            });


            
$j("span.refreshCoords").on("click", function() {
                
$j("span.refreshCoords").text("Refreshing...");
                
showLocations(); 
            });

            
localStorage.removeItem('lastEarnings');
            
retrieveEarnings();

        }
    });
}

function 
retrieveLastWeekEarnings(){
    
$j.ajax({
        
url'http://submit.shutterstock.com/show_component.mhtml?component_path=mobile/comps/earnings_overview.mj',
        
type"get",
        
dataType"html",
        
error: function (requeststatuserror) {
            
console.log(request.responseText);
        },
        
success: function( data ){
            if (
existsInLocalStorage('lastSevenDays'data)) {
                
retrieveEarnings();
                
$j("div.refreshCoords").text("Refresh");
                return 
true;
            }
            var 
res $j.parseJSON(data);  
            
// moramo ovako jer je asinkrono. dok u divu ispise tekst, ovo jos nije stiglo sa servera
            
if (res.last_7_days) {
                
$j("span#last7").text(res.last_7_days);
            }
            if (
res.day) {
                
$j("span#today").text(res.day);
            }
            
//      if (res.unpaid) {
            //          $j("span#unpaid").text(res.unpaid);
            //      }
            //      if (res.lifetime) {
            //          $j("span#lifetime").text(res.lifetime);
            //      }
        
}  
    }); 
}
// retreive earnings for last 7 days for each image: http://submit.shutterstock.com/show_component.mhtml?component_path=mobile/comps/earnings_list.mj
// and put that info in the appropriate DIV

function retrieveEarnings(){
    if (
displayRecentEarnings) {
        
$j.ajax({
            
url'http://submit.shutterstock.com/show_component.mhtml?component_path=mobile/comps/earnings_list.mj',
            
type"get",
            
dataType"html",
            
error: function (requeststatuserror) {
                
console.log(request.responseText);
            },
            
success: function( data ){

                if (
existsInLocalStorage('lastEarnings'data)) {
                    
$j("span.refreshCoords").text("Refresh");
                    return 
true;
                }

                var 
res $j.parseJSON(data);  

                var 
day=0// retrieve for today, will increase if <10 dls today
                
var retrievedImages 0// count number of retrieved, stop at 10

                
while (retrievedImages 10) {
                    var 
downloads res[day].downloads;
                    
$j.each(downloads, function (indel) {
                        var 
imageID el.photo_id;
                        var 
earnings el.payout;
                        var 
date el.download_date;
                        if (
debug) {console.log("ID: " imageID ", Earnings: " earnings ", Date: " date)};
                        
$j("span#earnings" imageID date ).text(earnings "$");
                        
retrievedImages++;
                        if (
retrievedImages >= 10) return false;
                    });
                    
day++;
                    if (
debugconsole.log(dayretrievedImages);
                }

            }
        }); 
    }
}





// following code created by https://gist.github.com/satinka/5479a93d389a07d41246

function ExtractLocation(details) { // created by https://gist.github.com/satinka/5479a93d389a07d41246
    
var loc "";
    var 
country "";
    var 
locality "";
    var 
admin_area1 "";
    var 
admin_area2 "";

    
$j.each(details, function( indel ) {
        if (
$j.inArray("country"el.types) != -1
            
country useShortCountryName el.short_name el.long_name;
        if (
$j.inArray("locality"el.types) != -1
            
locality el.long_name;
        if (
$j.inArray("administrative_area_level_1"el.types) != -1
            
admin_area1 el.short_name;
        if (
$j.inArray("administrative_area_level_2"el.types) != -1
            
admin_area2 el.long_name;
    });
    
loc loc + ((locality !== "") ? locality ", " "") +
        ((
admin_area2 != "") ? admin_area2 ", " "") +
        ((
admin_area1 != "") ? admin_area1 ", " "") +
        ((
country !== "") ? country "");
    return 
loc;
}

function 
createStyles() {
    var 
sheet = (function() {
        var 
style document.createElement("style");
        
style.appendChild(document.createTextNode(""));
        
document.head.appendChild(style);
        return 
style.sheet;
    })(); 
    var 
refreshCoords "cursor: hand; cursor: pointer; text-decoration: underline;";

    var 
ggDL "position: fixed; top: 60px; left: 50px; width: 200px; height: 95%; overflow: auto; z-index:3;" +
        
"border: 1px solid #eeeeee; background-color: white; resize: both;" +
        
"font-size: 11px;" +
        
"padding: 2px 3px 0 5px;" 
        
"text-shadow: 0 0 5px #fff; text-align: left;";

    
//   var map = "position: fixed; top: 60px; left: 320px; width: 1000px; height: 95%; overflow: auto; background-color: #eeeeee;";
    
addCSSRule(sheet"div#dragContainer"ggDL0);
    
addCSSRule(sheet"span.refreshCoords"refreshCoords0);
}

function 
addCSSRule(sheetselectorrulesindex) {
    if(
"insertRule" in sheet) {
        
sheet.insertRule(selector "{" rules "}"index);
    }
    else if(
"addRule" in sheet) {
        
sheet.addRule(selectorrulesindex);
    }
}

function 
sortByKey(array, key) {
    return array.
sort(function(ab) {
        var 
a[key]; var b[key];
        return ((
y) ? -: ((y) ? 0));
    });

ToBad вне форума   Ответить с цитированием
За это сообщение сказал спасибо:
Юрчелло (08.11.2017)
Старый 04.12.2016, 16:49   #30
Заблокирован(а) перманентно
 
Регистрация: 23.04.2011
Сообщения: 1,568
Репутация: 911
Оставлено благодарностей: 1,302
Получено благодарностей: 970
По умолчанию Re: User Scripts для Шаттерстока

Редактор мартышкин ругается на эту строчку:

Код:
var $j = jQuery.noConflict();

код брал здесь

и ещё в этой строке:
Код:
"text-shadow: 0 0 5px #fff; text-align: left;"
внес изменения:
Код:
"text-shadow: 0 2 1px #000; text-align: left;"
но поменялся только цвет, первые два ноля не параметры смещения тени разве?
____________________

С пикселями разобрался,
а с переменной:
Снимок экрана 2016-12-04 в 15.56.50.png
в принципе некритично как я понял, бо работает и так, но все же...))

Последний раз редактировалось ratamaque, 04.12.2016 в 17:04.
ratamaque вне форума   Ответить с цитированием
Ответ


Здесь присутствуют: 1 (пользователей - 0 , гостей - 1)
 
Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск
Опции просмотра

Ваши права в разделе
Вы не можете создавать темы
Вы не можете отвечать на сообщения
Вы не можете прикреплять файлы
Вы не можете редактировать сообщения

BB-коды Вкл.
Смайлы Вкл.
[IMG] код Вкл.
HTML код Выкл.
Быстрый переход


Часовой пояс GMT +4, время: 20:12.


©2006-2010 Microstock.ru   Powered by vBulletin® Copyright ©2000-2008, Jelsoft Enterprises Ltd.   Перевод: zCarot