intel-screenbot

An Ingress Intel Map Bot for Hangoutsbot
git clone git://archive.git.mtrnord.blog/MTRNord/intel-screenbot.git
Log | Files | Refs | README | LICENSE

commit 5dadd1d7f9e4d66ae6437aeaa70a26c24c667ee3
parent f320f6c79a6df088241e8e71bb70560ab82b9407
Author: Marcel <MTRNord@users.noreply.github.com>
Date:   Sat, 10 Dec 2016 20:59:44 +0100

Merge pull request #4 from MTRNord/IntelToIITC

Intel to iitc
Diffstat:
M__init__.py | 166++++++++++++++++++++++++++++++++++++++++++++-----------------------------------
Ascreencap.js | 537+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Dscreencap_iitc.js | 515-------------------------------------------------------------------------------
Dscreencap_intel.js | 438-------------------------------------------------------------------------------
4 files changed, 629 insertions(+), 1027 deletions(-)

diff --git a/__init__.py b/__init__.py @@ -86,31 +86,12 @@ def _get_lines(shell_command): return p.returncode, output, True @asyncio.coroutine -def _screencap(maptype, url, filepath, filename, SACSID, CSRF, plugins, search, bot, event): +def _screencap(url, args_filepath, filepath, filename, bot, event): loop = asyncio.get_event_loop() - logger.info("screencapping {} and saving as {}".format(url, filepath)) - if plugins is '': - if search == False: - command = 'phantomjs hangupsbot/plugins/intel_screenbot/screencap_' + maptype + '.js "' + SACSID + '" "' + CSRF + '" "' + url + '" "' + filepath + '"' - task = _get_lines(command) - task = asyncio.wait_for(task, 420.0) - exitcode, output, status = yield from task - else: - command = 'phantomjs hangupsbot/plugins/intel_screenbot/screencap_' + maptype + '.js "' + SACSID + '" "' + CSRF + '" "' + url + '" "' + filepath + '" "' + search + '"' - task = _get_lines(command) - task = asyncio.wait_for(task, 420.0) - exitcode, output, status = yield from task - else: - if search == False: - command = 'phantomjs hangupsbot/plugins/intel_screenbot/screencap_' + maptype + '.js "' + SACSID + '" "' + CSRF + '" "' + url + '" "' + filepath + '" "' + plugins + '"' - task = _get_lines(command) - task = asyncio.wait_for(task, 420.0) - exitcode, output, status = yield from task - else: - command = 'phantomjs hangupsbot/plugins/intel_screenbot/screencap_' + maptype + '.js "' + SACSID + '" "' + CSRF + '" "' + url + '" "' + filepath + '" "' + search + '" "' + plugins + '"' - task = _get_lines(command) - task = asyncio.wait_for(task, 420.0) - exitcode, output, status = yield from task + command = 'phantomjs hangupsbot/plugins/intel_screenbot/screencap.js "' + args_filepath + '"' + task = _get_lines(command) + task = asyncio.wait_for(task, 420.0) + exitcode, output, status = yield from task # read the resulting file into a byte array # yield from asyncio.sleep(10) @@ -149,6 +130,8 @@ def intel(bot, event, *args): """get a screenshot of a search term or intel URL or the default intel URL of the hangout. """ + arguments = {} + if args: if len(args) > 1: url = ' '.join(str(i) for i in args) @@ -159,22 +142,17 @@ def intel(bot, event, *args): else: url = bot.conversation_memory_get(event.conv_id, 'IntelURL') - if bot.config.exists(["intel_screenbot", "SACSID"]): - if bot.config.exists(["intel_screenbot", "CSRF"]): - SACSID = bot.config.get_by_path(["intel_screenbot", "SACSID"]) - CSRF = bot.config.get_by_path(["intel_screenbot", "CSRF"]) - else: - html = "<i><b>{}</b> No Intel password has been added to config. Unable to authenticate".format(event.user.full_name) - yield from bot.coro_send_message(event.conv, html) - elif bot.config.exists(["intel_screenbot", "email"]): + if bot.config.exists(["intel_screenbot", "email"]): if bot.config.exists(["intel_screenbot", "password"]): - SACSID = bot.config.get_by_path(["intel_screenbot", "email"]) - CSRF = bot.config.get_by_path(["intel_screenbot", "password"]) + email = bot.config.get_by_path(["intel_screenbot", "email"]) + password = bot.config.get_by_path(["intel_screenbot", "password"]) + arguments['email'] = email + arguments['password'] = password else: html = "<i><b>{}</b> No Intel password has been added to config. Unable to authenticate".format(event.user.full_name) yield from bot.coro_send_message(event.conv, html) else: - html = "<i><b>{}</b> No Intel SACSID Cookie or Email/password has been added to config. Unable to authenticate".format(event.user.full_name) + html = "<i><b>{}</b> No Intel Email/password has been added to config. Unable to authenticate".format(event.user.full_name) yield from bot.coro_send_message(event.conv, html) if url is None: @@ -182,29 +160,53 @@ def intel(bot, event, *args): yield from bot.coro_send_message(event.conv, html) else: - if re.match(r'^[a-zA-Z]+://', url): - search = False - ZoomSearch = re.finditer(r"(?:&z=).*", url) - for matchNum, zoomlevel_raw in enumerate(ZoomSearch): - matchNum = matchNum + 1 - zoomlevel_clean = zoomlevel_raw.group() - zoomlevel = zoomlevel_clean[3:][:2] - if zoomlevel.isdigit(): - yield from bot.coro_send_message(event.conv_id, "<i>intel map at zoom level "+ zoomlevel + " requested, please wait...</i>") + if re.match(r'(http(s)?:\/\/)', url): + search = 'nix' + zoomParameter = re.search(r"(?:&z=)", url, re.IGNORECASE) + if zoomParameter: + ZoomSearch = re.finditer(r"(?:&z=).*", url, flags=re.I) + for matchNum, zoomlevel_raw in enumerate(ZoomSearch): + matchNum = matchNum + 1 + zoomlevel_clean = zoomlevel_raw.group() + zoomlevel = zoomlevel_clean[3:][:2] + if zoomlevel.isdigit(): + yield from bot.coro_send_message(event.conv_id, "<i>intel map at zoom level "+ zoomlevel + " requested, please wait...</i>") else: yield from bot.coro_send_message(event.conv_id, "<i>intel map at last zoom level requested, please wait...</i>") else: search = url - logger.info(search); + zoomParameter = re.search(r"(?<=z=)", url, re.IGNORECASE) + if zoomParameter: + ZoomSearch = re.finditer(r"(?<=z=)[^\s]+", url, flags=re.I) + for matchNum, zoomlevel_raw in enumerate(ZoomSearch): + matchNum = matchNum + 1 + zoomlevel = zoomlevel_raw.group() + search = search.replace("z={}".format(zoomlevel),"") + if zoomlevel.isdigit(): + yield from bot.coro_send_message(event.conv_id, "<i>intel map is searching " + search + " and screenshooting at zoom level "+ zoomlevel + " as requested, please wait...</i>") + arguments['zoomlevel'] = str(zoomlevel) + else: + yield from bot.coro_send_message(event.conv_id, "<i>intel map is searching " + search + " and screenshooting as requested, please wait...</i>") url = 'https://www.ingress.com/intel' - yield from bot.coro_send_message(event.conv_id, "<i>intel map is searching " + search + " and screenshooting as requested, please wait...</i>") filepath = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name filename = filepath.split('/', filepath.count('/'))[-1] + args_filepath = tempfile.NamedTemporaryFile(prefix="args_{}".format(event.conv_id), suffix=".json", delete=False).name logger.debug("temporary screenshot file: {}".format(filepath)) + logger.debug("temporary args file: {}".format(args_filepath)) + + arguments['search'] = search + arguments['url'] = url + arguments['filepath'] = filepath + arguments['maptype'] = "intel" + + with open(args_filepath, 'w') as out: + out.write(json.dumps(arguments)) + + try: loop = asyncio.get_event_loop() - image_data = yield from _screencap("intel", url, filepath, filename, SACSID, CSRF, "", search, bot, event) + image_data = yield from _screencap(url, args_filepath, filepath, filename, bot, event) except Exception as e: yield from bot.coro_send_message(event.conv_id, "<i>error getting screenshot</i>") logger.exception("screencap failed".format(url)) @@ -215,6 +217,8 @@ def iitc(bot, event, *args): """get a screenshot of a search term or intel URL or the default intel URL of the hangout. """ + arguments = {} + if args: if len(args) > 1: url = ' '.join(str(i) for i in args) @@ -225,50 +229,58 @@ def iitc(bot, event, *args): else: url = bot.conversation_memory_get(event.conv_id, 'IntelURL') - if bot.config.exists(["intel_screenbot", "SACSID"]): - if bot.config.exists(["intel_screenbot", "CSRF"]): - SACSID = bot.config.get_by_path(["intel_screenbot", "SACSID"]) - CSRF = bot.config.get_by_path(["intel_screenbot", "CSRF"]) - else: - html = "<i><b>{}</b> No Intel password has been added to config. Unable to authenticate".format(event.user.full_name) - yield from bot.coro_send_message(event.conv, html) - elif bot.config.exists(["intel_screenbot", "email"]): + if bot.config.exists(["intel_screenbot", "email"]): if bot.config.exists(["intel_screenbot", "password"]): - SACSID = bot.config.get_by_path(["intel_screenbot", "email"]) - CSRF = bot.config.get_by_path(["intel_screenbot", "password"]) + email = bot.config.get_by_path(["intel_screenbot", "email"]) + password = bot.config.get_by_path(["intel_screenbot", "password"]) + arguments['email'] = email + arguments['password'] = password else: html = "<i><b>{}</b> No Intel password has been added to config. Unable to authenticate".format(event.user.full_name) yield from bot.coro_send_message(event.conv, html) else: - html = "<i><b>{}</b> No Intel SACSID Cookie or Email/password has been added to config. Unable to authenticate".format(event.user.full_name) + html = "<i><b>{}</b> No Intel Email/password has been added to config. Unable to authenticate".format(event.user.full_name) yield from bot.coro_send_message(event.conv, html) - + if url is None: html = "<i><b>{}</b> No Intel URL has been set for screenshots.".format(event.user.full_name) yield from bot.coro_send_message(event.conv, html) else: - if re.match(r'^[a-zA-Z]+://', url): - search = False - ZoomSearch = re.finditer(r"(?:&z=).*", url) - for matchNum, zoomlevel_raw in enumerate(ZoomSearch): - matchNum = matchNum + 1 - zoomlevel_clean = zoomlevel_raw.group() - zoomlevel = zoomlevel_clean[3:][:2] - if zoomlevel.isdigit(): - yield from bot.coro_send_message(event.conv_id, "<i>intel map at zoom level "+ zoomlevel + " requested, please wait...</i>") + if re.match(r'(http(s)?:\/\/)', url): + search = 'nix' + zoomParameter = re.search(r"(?:&z=)", test_str, re.IGNORECASE) + if zoomParameter: + ZoomSearch = re.finditer(r"(?:&z=).*", url, flags=re.I) + for matchNum, zoomlevel_raw in enumerate(ZoomSearch): + matchNum = matchNum + 1 + zoomlevel_clean = zoomlevel_raw.group() + zoomlevel = zoomlevel_clean[3:][:2] + if zoomlevel.isdigit(): + yield from bot.coro_send_message(event.conv_id, "<i>intel map at zoom level "+ zoomlevel + " requested, please wait...</i>") else: yield from bot.coro_send_message(event.conv_id, "<i>intel map at last zoom level requested, please wait...</i>") else: search = url - logger.info(search); + zoomParameter = re.search(r"(?<=z=)", url, re.IGNORECASE) + if zoomParameter: + ZoomSearch = re.finditer(r"(?<=z=)[^\s]+", url, flags=re.I) + for matchNum, zoomlevel_raw in enumerate(ZoomSearch): + matchNum = matchNum + 1 + zoomlevel = zoomlevel_raw.group() + search = search.replace("z={}".format(zoomlevel),"") + if zoomlevel.isdigit(): + yield from bot.coro_send_message(event.conv_id, "<i>intel map is searching " + search + " and screenshooting at zoom level "+ zoomlevel + " as requested, please wait...</i>") + arguments['zoomlevel'] = str(zoomlevel) + else: + yield from bot.coro_send_message(event.conv_id, "<i>intel map is searching " + search + " and screenshooting as requested, please wait...</i>") url = 'https://www.ingress.com/intel' - yield from bot.coro_send_message(event.conv_id, "<i>intel map is searching " + search + " and screenshooting as requested, please wait...</i>") filepath = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name filename = filepath.split('/', filepath.count('/'))[-1] - plugins_filepath = tempfile.NamedTemporaryFile(prefix=event.conv_id, suffix=".json", delete=False).name + args_filepath = tempfile.NamedTemporaryFile(prefix="args_{}".format(event.conv_id), suffix=".json", delete=False).name logger.debug("temporary screenshot file: {}".format(filepath)) + logger.debug("temporary args file: {}".format(args_filepath)) if bot.conversation_memory_get(event.conv_id, 'iitc_plugins'): plugins = [] plugin_names = bot.conversation_memory_get(event.conv_id, 'iitc_plugins').split(", ") @@ -280,12 +292,18 @@ def iitc(bot, event, *args): else: plugins = '' - with open(plugins_filepath, 'w') as out: - out.write(json.dumps(plugins)) + arguments['plugins'] = plugins + arguments['search'] = search + arguments['url'] = url + arguments['filepath'] = filepath + arguments['maptype'] = "iitc" + + with open(args_filepath, 'w') as out: + out.write(json.dumps(arguments)) try: loop = asyncio.get_event_loop() - image_data = yield from _screencap("iitc", url, filepath, filename, SACSID, CSRF, plugins_filepath, search, bot, event) + image_data = yield from _screencap(url, args_filepath, filepath, filename, bot, event) except Exception as e: yield from bot.coro_send_message(event.conv_id, "<i>error getting screenshot</i>") logger.exception("screencap failed".format(url)) diff --git a/screencap.js b/screencap.js @@ -0,0 +1,537 @@ +var system = require('system'); +var args = system.args; +var page = require('webpage').create(); +var fs = require('fs'); +var cookiespath = '.iced_cookies'; +var config = ''; +var loginTimeout = '5000'; +if (args.length === 1) { + console.log('Try to pass some args when invoking this script!'); +} else { + var arguments_file = args[1]; + var arguments = JSON.parse(fs.read(arguments_file)); + if (arguments.hasOwnProperty('plugins')) { + var plugins = arguments["plugins"] + } + if (arguments.hasOwnProperty('zoomlevel')) { + var zoomlevel = arguments["zoomlevel"] + } + var maptype = arguments["maptype"] + var search = arguments["search"] + var url = arguments["url"] + var filepath = arguments['filepath'] + var user = arguments['email'] + var pass = arguments['password'] +} +function quit() { + phantom.exit(0); +} + +loadCookies(function() { + if (config.SACSID == undefined || config.SACSID == '') { + firePlainLogin(user, pass, url); + } else { + addCookies(config.SACSID, config.CSRF); + console.log('Using cookies to log in'); + afterCookieLogin(url, search); + } +}); + + +function loadCookies(callback) { + if(fs.exists(cookiespath)) { + var stream = fs.open(cookiespath, 'r'); + + while(!stream.atEnd()) { + var line = stream.readLine().split('='); + if(line[0] === 'SACSID') { + config.SACSID = line[1]; + } else if(line[0] === 'csrftoken') { + config.CSRF = line[1]; + } else { + config.SACSID = ''; + config.CSRF = ''; + } + } + stream.close(); + } + callback(); +} + +function isSignedIn() { + return page.evaluate(function() { + return document.getElementsByTagName('a')[0].innerText.trim() !== 'Sign in'; + }); +} + +function storeCookies() { + var cookies = page.cookies; + fs.write(cookiespath, '', 'w'); + for(var i in cookies) { + fs.write(cookiespath, cookies[i].name + '=' + cookies[i].value +'\n', 'a'); + } +} + +function firePlainLogin(user, pass, url) { + page.open('https://www.ingress.com/intel', function (status) { + page.evaluate(function () { + localStorage.clear() + }); + if (status !== 'success') {console.log("Login ERROR"); quit();} + var link = 'https://www.google.com/accounts/ServiceLogin?service=ah&passive=true&continue=https://appengine.google.com/_ah/conflogin%3Fcontinue%3Dhttps://www.ingress.com/intel&ltmpl=' + page.open(link, function () { + login(user, pass, url); + }); + }); +} + +function login(l, p, url) { + if (document.querySelector('#timeoutError')){ + firePlainLogin(l, p) + } + waitFor({ + timeout: loginTimeout*2, + check: function () { + return page.evaluate(function() { + if (document.querySelector('#gaia_loginform')) { + return true; + }else{ + return false; + } + }); + }, + success: function () { + page.evaluate(function (l) { + document.getElementById('Email').value = l; + }, l); + page.evaluate(function () { + document.querySelector("#next").click(); + }); + window.setTimeout(function () { + page.evaluate(function (p) { + document.getElementById('Passwd').value = p; + }, p); + if(document.querySelector("#next")){ + page.evaluate(function () { + document.querySelector("#next").click(); + }); + }else{ + page.evaluate(function () { + document.querySelector("#signIn").click(); + }); + } + window.setTimeout(function () { + if (page.url.substring(0,40) === 'https://accounts.google.com/ServiceLogin') { + console.log("login failed: wrong email and/or password") + quit() + } + + if (page.url.substring(0,40) === 'https://appengine.google.com/_ah/loginfo') { + page.evaluate(function () { + document.getElementById('persist_checkbox').checked = true; + document.getElementsByTagName('form').submit(); + }); + } + + if (page.url.substring(0,44) === 'https://accounts.google.com/signin/challenge') { + twostep = system.stdin.readLine(); + } + window.setTimeout(afterPlainLogin(url, search), loginTimeout); + }, loginTimeout) + }, loginTimeout / 10); + }, + error: function () { + console.log("error waitingFor loginform") + quit(); + } + }); +} + +function afterPlainLogin(url, search) { + page.viewportSize = { width: '1280', height: '720' }; + page.open(url, function(status) { + console.log(url) + if (status !== 'success') {console.log('unable to connect to remote server afterPlainLogin'); quit()} + if (!isSignedIn()) { + console.log("not logged in") + quit(); + } + setTimeout(function() { + storeCookies(); + setupIITC() + setTimeout(function() { + setTimeout(function() { + if (search != 'nix') { + searchfunc(search); + } + }, 1000); + waitFor({ + timeout: 240000, + check: function () { + return page.evaluate(function(zoomlevel) { + if (typeof zoomlevel === 'undefined' || zoomlevel === null) { + window.map.setZoom(zoomlevel,animate=false) + } + if (document.querySelector('.map').textContent.indexOf('done') != -1) { + return true; + }else{ + console.log('generateFakeOutput') + return false; + } + }, zoomlevel); + }, + success: function () { + var startTime = new Date().getTime(); + var interval = setInterval(function(){ + if(new Date().getTime() - startTime > 5000){ + hideDebris(); + prepare('1280', '720'); + main(); + clearInterval(interval); + return; + } + console.log('generateFakeOutput') + }, 1000); + }, + error: function () { + var startTime = new Date().getTime(); + var interval = setInterval(function(){ + if(new Date().getTime() - startTime > 5000){ + hideDebris(); + prepare('1280', '720'); + main(); + clearInterval(interval); + return; + } + console.log('generateFakeOutput') + }, 1000); + } + }); + }, "1000"); + }, "1000"); + }); +} + + + +function addCookies(sacsid, csrf) { + phantom.addCookie({ + name: 'SACSID', + value: sacsid, + domain: 'www.ingress.com', + path: '/', + httponly: true, + secure: true + }); + phantom.addCookie({ + name: 'csrftoken', + value: csrf, + domain: 'www.ingress.com', + path: '/' + }); +} + + +function waitFor ($config) { + $config._start = $config._start || new Date(); + if ($config.timeout && new Date - $config._start > $config.timeout) { + if ($config.error) $config.error(); + return; + } + if ($config.check()) { + return $config.success(); + } + setTimeout(waitFor, $config.interval || 0, $config); +} + +function loadIitcPlugin(src) { + page.evaluate(function(src) { + var script = document.createElement('script'); + script.type='text/javascript'; + script.src=src; + document.head.insertBefore(script, document.head.lastChild); + }, src); +} + +function loadLocalIitcPlugin(src) { + page.injectJs(src) +} + +function afterCookieLogin(url, search) { + page.viewportSize = { width: '1280', height: '720' }; + page.open(url, function(status) { + if (status !== 'success') {quit('unable to connect to remote server')} + if(!isSignedIn()) { + if(fs.exists(cookiespath)) { + fs.remove(cookiespath); + } + quit('Cookies are obsolete. Update your config file.'); + } + setTimeout(function() { + setupIITC() + setTimeout(function() { + if (search != "nix") { + searchfunc(search); + } + waitFor({ + timeout: 240000, + check: function () { + return page.evaluate(function() { + if (document.querySelector('.map').textContent.indexOf('done') != -1) { + return true; + }else{ + console.log('generateFakeOutput') + return false; + } + }); + }, + success: function () { + var startTime = new Date().getTime(); + var interval = setInterval(function(){ + if(new Date().getTime() - startTime > 5000){ + hideDebris(); + prepare('1280', '720'); + main(); + clearInterval(interval); + return; + } + console.log('generateFakeOutput') + }, 1000); + }, + error: function () { + var startTime = new Date().getTime(); + var interval = setInterval(function(){ + if(new Date().getTime() - startTime > 5000){ + hideDebris(); + prepare('1280', '720'); + main(); + clearInterval(interval); + return; + } + console.log('generateFakeOutput') + }, 1000); + } + }); + }, "1000"); + }, "1000"); + }); +} + +function searchfunc(search){ + page.evaluate(function(search, zoomlevel) { + if (document.querySelector('#search')){ + window.addHook('search', function(query) { + var checkExist = setInterval(function() { + if (query.results.length > 0) { + console.warn(query.results) + map.fitBounds(query.results[0].bounds, {maxZoom: 17}) + clearInterval(checkExist); + } + if (typeof zoomlevel !== 'undefined' || zoomlevel !== null) { + console.log(zoomlevel) + window.map.setZoom(zoomlevel,animate=false) + } + }, 100); + }); + setTimeout(function() { + window.search.doSearch(search, true) + }, 2000); + } + }, search, zoomlevel); +} + +function setupIITC(){ + loadIitcPlugin('https://static.iitc.me/build/release/plugins/canvas-render.user.js'); + page.evaluate(function(maptype) { + localStorage['ingress.intelmap.layergroupdisplayed'] = JSON.stringify({ + "Unclaimed Portals": true, + "Level 1 Portals": true, + "Level 2 Portals": true, + "Level 3 Portals": true, + "Level 4 Portals": true, + "Level 5 Portals": true, + "Level 6 Portals": true, + "Level 7 Portals": true, + "Level 8 Portals": true, + "Fields": true, + "Links": true, + "Resistance": true, + "Enlightened": true, + "DEBUG Data Tiles":false, + "Artifacts":true, + "Ornaments":true + }); + var script = document.createElement('script'); + script.type='text/javascript'; + script.src='https://static.iitc.me/build/test/total-conversion-build.user.js'; + document.head.insertBefore(script, document.head.lastChild); + if (maptype == "intel") { + localStorage['iitc-base-map'] = 'Google Default Ingress Map'; + }else { + localStorage['iitc-base-map'] = 'Google Roads'; + } + }, maptype); + if (maptype != "intel") { + console.log(plugins); + for(var i in plugins){ + var plugin = plugins[i]; + if(plugin.match('(http(s)?:\/\/)')){ + loadIitcPlugin(plugin); + }else{ + loadLocalIitcPlugin(plugin); + } + } + } +} + +function s(file) { + console.log('SCREENSHOT') + page.render(file); + var startTime = new Date().getTime(); + var startTime = new Date().getTime(); + var interval = setInterval(function(){ + if(new Date().getTime() - startTime > 5000){ + clearInterval(interval); + quit(); + return; + } + console.log('doSomeOutput') + }, 1000); +} + +function hideDebris() { + window.setTimeout(function() { + page.evaluate(function() { + if (document.querySelector('#chat')) {document.querySelector('#chat').style.display = 'none';} + if (document.querySelector('#chatcontrols')) {document.querySelector('#chatcontrols').style.display = 'none';} + if (document.querySelector('#chatinput')) {document.querySelector('#chatinput').style.display = 'none';} + if (document.querySelector('#updatestatus')) {document.querySelector('#updatestatus').style.display = 'none';} + if (document.querySelector('#sidebartoggle')) {document.querySelector('#sidebartoggle').style.display = 'none';} + if (document.querySelector('#scrollwrapper')) {document.querySelector('#scrollwrapper').style.display = 'none';} + if (document.querySelector('.leaflet-control-container')) {document.querySelector('.leaflet-control-container').style.display = 'none';} + if (document.querySelector('#portal_highlight_select')) {document.querySelector('#portal_highlight_select').style.display = 'none';} + }); + }, 200); +} + +function prepare(widthz, heightz) { + window.setTimeout(function() { + page.evaluate(function(w, h) { + var water = document.createElement('p'); + water.id='viewport-ice'; + water.style.position = 'absolute'; + water.style.top = '0'; + water.style.marginTop = '0'; + water.style.paddingTop = '0'; + water.style.left = '0'; + water.style.width = w + 'px'; + water.style.height = h + 'px'; + document.querySelectorAll('body')[0].appendChild(water); + }, widthz, heightz); + var selector = "#viewport-ice"; + setElementBounds(selector); + }, 500); +} + + +function setElementBounds(selector) { + page.clipRect = page.evaluate(function(selector) { + var clipRect = document.querySelector(selector).getBoundingClientRect(); + return { + top: clipRect.top, + left: clipRect.left, + width: clipRect.width, + height: clipRect.height + }; + }, selector); +} + +function getDateTime(format) { + var now = new Date(); + var year = now.getFullYear(); + var month = now.getMonth()+1; + var day = now.getDate(); + var hour = now.getHours(); + var minute = now.getMinutes(); + var second = now.getSeconds(); + var timeZone = ''; + if(month.toString().length === 1) { + month = '0' + month; + } + if(day.toString().length === 1) { + day = '0' + day; + } + if(hour.toString().length === 1) { + hour = '0' + hour; + } + if(minute.toString().length === 1) { + minute = '0' + minute; + } + if(second.toString().length === 1) { + second = '0' + second; + } + var dateTime; + if (format === 1) { + dateTime = year + '-' + month + '-' + day + '--' + hour + '-' + minute + '-' + second; + } else { + dateTime = day + '.' + month + '.' + year + ' ' + hour + ':' + minute + ':' + second + timeZone; + } + return dateTime; +} + +function addTimestamp(time) { + if (maptype == "iitc") { + page.evaluate(function(dateTime, search) { + var water = document.createElement('p'); + water.id='watermark-ice'; + water.innerHTML = dateTime + ' - ' + search; + water.style.position = 'absolute'; + water.style.color = '#3A539B'; + water.style.top = '0'; + water.style.zIndex = '4404'; + water.style.marginTop = '0'; + water.style.paddingTop = '0'; + water.style.left = '0'; + water.style.fontSize = '40px'; + water.style.opacity = '0.8'; + water.style.fontFamily = 'monospace'; + water.style.textShadow = '0px 1px 8px rgba(150, 150, 150, 1)'; + document.querySelectorAll('body')[0].appendChild(water); + }, time, search); + }else { + page.evaluate(function(dateTime, search) { + var water = document.createElement('p'); + water.id='watermark-ice'; + water.style.zIndex = '4404'; + water.innerHTML = dateTime + ' - ' + search; + water.style.position = 'absolute'; + water.style.color = 'orange'; + water.style.top = '0'; + water.style.left = '0'; + water.style.fontSize = '40px'; + water.style.opacity = '0.8'; + water.style.marginTop = '0'; + water.style.paddingTop = '0'; + water.style.fontFamily = 'monospace'; + water.style.textShadow = '0px 1px 8px rgba(150, 150, 150, 1)'; + document.querySelectorAll('body')[0].appendChild(water); + }, time, search); + } +} + +/** + * Main function. + */ +function main() { + page.evaluate(function() { + if (document.getElementById('watermark-ice')) { + var oldStamp = document.getElementById('watermark-ice'); + oldStamp.parentNode.removeChild(oldStamp); + } + }); + window.setTimeout(function() { + addTimestamp(getDateTime(0)); + file = filepath; + s(file); + }, 400); +} diff --git a/screencap_iitc.js b/screencap_iitc.js @@ -1,515 +0,0 @@ -var system = require('system'); -var args = system.args; -var page = require('webpage').create(); -var fs = require('fs'); -var cookiespath = '.iced_cookies'; -var config = ''; -if (args.length === 1) { - console.log('Try to pass some args when invoking this script!'); -} else { - if (args.length === 6){ - var SACSID = args[1]; - var CSRF = args[2]; - var IntelURL = args[3]; - var filepath = args[4]; - var plugins_file = args[5]; - var search = 'nix'; - var loginTimeout = '5000'; - }else{ - if (args.length === 7){ - var SACSID = args[1]; - var CSRF = args[2]; - var IntelURL = args[3]; - var filepath = args[4]; - var search = args[5]; - var plugins_file = args[6]; - var loginTimeout = '5000'; - } - } -} - -function validateEmail(email) { - var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - return re.test(email); -} - -function quit(err) { - phantom.exit(0); -} -if (validateEmail(SACSID)) { - loadCookies(function() { - if (config.SACSID == undefined || config.SACSID == '') { - firePlainLogin(SACSID, CSRF); - } else { - addCookies(config.SACSID, config.CSRF); - console.log('Using cookies to log in'); - afterCookieLogin(); - } - }); -}else { - addCookies(SACSID, CSRF); - afterCookieLogin(IntelURL, search); -} - -function loadCookies(callback) { - if(fs.exists(cookiespath)) { - var stream = fs.open(cookiespath, 'r'); - - while(!stream.atEnd()) { - var line = stream.readLine().split('='); - if(line[0] === 'SACSID') { - config.SACSID = line[1]; - } else if(line[0] === 'csrftoken') { - config.CSRF = line[1]; - } else { - config.SACSID = ''; - config.CSRF = ''; - } - } - stream.close(); - } - callback(); -} - -function isSignedIn() { - return page.evaluate(function() { - return document.getElementsByTagName('a')[0].innerText.trim() !== 'Sign in'; - }); -} - -function storeCookies() { - var cookies = page.cookies; - fs.write(cookiespath, '', 'w'); - for(var i in cookies) { - fs.write(cookiespath, cookies[i].name + '=' + cookies[i].value +'\n', 'a'); - } -} - -function firePlainLogin(SACSID, CSRF) { - page.open('https://www.ingress.com/intel', function (status) { - page.evaluate(function () { - localStorage.clear() - }); - if (status !== 'success') {quit('unable to connect to remote server')} - var link = 'https://www.google.com/accounts/ServiceLogin?service=ah&passive=true&continue=https://appengine.google.com/_ah/conflogin%3Fcontinue%3Dhttps://www.ingress.com/intel&ltmpl=' - page.open(link, function () { - login(SACSID, CSRF); - }); - }); -} - -function login(l, p) { - if (document.querySelector('#timeoutError')){ - login(l, p) - firePlainLogin(l, p) - } - waitFor({ - timeout: loginTimeout*2, - check: function () { - return page.evaluate(function() { - if (document.querySelector('#gaia_loginform')) { - return true; - }else{ - return false; - } - }); - }, - success: function () { - page.evaluate(function (l) { - document.getElementById('Email').value = l; - }, l); - page.evaluate(function () { - document.querySelector("#next").click(); - }); - window.setTimeout(function () { - page.evaluate(function (p) { - document.getElementById('Passwd').value = p; - }, p); - if(document.querySelector("#next")){ - page.evaluate(function () { - document.querySelector("#next").click(); - }); - }else{ - page.evaluate(function () { - document.querySelector("#signIn").click(); - }); - } - window.setTimeout(function () { - if (page.url.substring(0,40) === 'https://accounts.google.com/ServiceLogin') { - quit('login failed: wrong email and/or password'); - } - - if (page.url.substring(0,40) === 'https://appengine.google.com/_ah/loginfo') { - page.evaluate(function () { - document.getElementById('persist_checkbox').checked = true; - document.getElementsByTagName('form').submit(); - }); - } - - if (page.url.substring(0,44) === 'https://accounts.google.com/signin/challenge') { - twostep = system.stdin.readLine(); - } - window.setTimeout(afterPlainLogin(IntelURL, search), loginTimeout); - }, loginTimeout) - }, loginTimeout / 10); - }, - error: function () { - quit(); - } - }); -} - -function afterPlainLogin(IntelURL, search) { - page.viewportSize = { width: '1280', height: '720' }; - page.open(IntelURL, function(status) { - if (status !== 'success') {quit('unable to connect to remote server')} - if (!isSignedIn()) { - console.log("not logged in") - quit(); - } - setTimeout(function() { - setupIITC() - setTimeout(function() { - setTimeout(function() {if (search != "nix") {searchfunc(search);}}, 1000); - waitFor({ - timeout: 240000, - check: function () { - return page.evaluate(function() { - if (document.querySelector('.map').textContent.indexOf('done') != -1) { - return true; - }else{ - console.log('generateFakeOutput') - return false; - } - }); - }, - success: function () { - var startTime = new Date().getTime(); - var interval = setInterval(function(){ - if(new Date().getTime() - startTime > 5000){ - hideDebris(); - prepare('1280', '720'); - main(); - clearInterval(interval); - return; - } - console.log('generateFakeOutput') - }, 1000); - }, - error: function () { - var startTime = new Date().getTime(); - var interval = setInterval(function(){ - if(new Date().getTime() - startTime > 5000){ - hideDebris(); - prepare('1280', '720'); - main(); - clearInterval(interval); - return; - } - console.log('generateFakeOutput') - }, 1000); - } - }); - }, "1000"); - }, "1000"); - }); -} - - - -function addCookies(sacsid, csrf) { - phantom.addCookie({ - name: 'SACSID', - value: sacsid, - domain: 'www.ingress.com', - path: '/', - httponly: true, - secure: true - }); - phantom.addCookie({ - name: 'csrftoken', - value: csrf, - domain: 'www.ingress.com', - path: '/' - }); -} - - -function waitFor ($config) { - $config._start = $config._start || new Date(); - if ($config.timeout && new Date - $config._start > $config.timeout) { - if ($config.error) $config.error(); - return; - } - if ($config.check()) { - return $config.success(); - } - setTimeout(waitFor, $config.interval || 0, $config); -} - -function loadIitcPlugin(src) { - page.evaluate(function(src) { - var script = document.createElement('script'); - script.type='text/javascript'; - script.src=src; - document.head.insertBefore(script, document.head.lastChild); - }, src); -} - -function loadLocalIitcPlugin(src) { - page.injectJs(src) -} - -function afterCookieLogin(IntelURL, search) { - page.viewportSize = { width: '1280', height: '720' }; - page.open(IntelURL, function(status) { - if (status !== 'success') {quit('unable to connect to remote server')} - if(!isSignedIn()) { - if(fs.exists(cookiespath)) { - fs.remove(cookiespath); - } - if(validateEmail(SACSID)) { - page.deleteCookie('SACSID'); - page.deleteCookie('csrftoken'); - firePlainLogin(SACSID, CSRF); - return; - } else { - quit('Cookies are obsolete. Update your config file.'); - } - } - setTimeout(function() { - setupIITC() - setTimeout(function() { - if (search != "nix") {searchfunc(search);} - waitFor({ - timeout: 240000, - check: function () { - return page.evaluate(function() { - if (document.querySelector('.map').textContent.indexOf('done') != -1) { - return true; - }else{ - console.log('generateFakeOutput') - return false; - } - }); - }, - success: function () { - var startTime = new Date().getTime(); - var interval = setInterval(function(){ - if(new Date().getTime() - startTime > 5000){ - hideDebris(); - prepare('1280', '720'); - main(); - clearInterval(interval); - return; - } - console.log('generateFakeOutput') - }, 1000); - }, - error: function () { - var startTime = new Date().getTime(); - var interval = setInterval(function(){ - if(new Date().getTime() - startTime > 5000){ - hideDebris(); - prepare('1280', '720'); - main(); - clearInterval(interval); - return; - } - console.log('generateFakeOutput') - }, 1000); - } - }); - }, "1000"); - }, "1000"); - }); -} - -function searchfunc(search){ - page.evaluate(function(search) { - if (document.querySelector('#search')){ - window.addHook('search', function(query) { - var checkExist = setInterval(function() { - if (query.results.length > 0) { - console.warn(query.results) - map.fitBounds(query.results[0].bounds, {maxZoom: 17}) - clearInterval(checkExist); - } - }, 100); - }); - setTimeout(function() { - window.search.doSearch(search, true) - }, 2000); - } - }, search); -} - -function setupIITC(){ - loadIitcPlugin('https://static.iitc.me/build/release/plugins/canvas-render.user.js'); - page.evaluate(function() { - localStorage['ingress.intelmap.layergroupdisplayed'] = JSON.stringify({ - "Unclaimed Portals": true, - "Level 1 Portals": true, - "Level 2 Portals": true, - "Level 3 Portals": true, - "Level 4 Portals": true, - "Level 5 Portals": true, - "Level 6 Portals": true, - "Level 7 Portals": true, - "Level 8 Portals": true, - "Fields": true, - "Links": true, - "Resistance": true, - "Enlightened": true, - "DEBUG Data Tiles":false, - "Artifacts":true, - "Ornaments":true - }); - var script = document.createElement('script'); - script.type='text/javascript'; - script.src='https://static.iitc.me/build/test/total-conversion-build.user.js'; - document.head.insertBefore(script, document.head.lastChild); - localStorage['iitc-base-map'] = 'Google Roads'; - }); - var plugins = JSON.parse(fs.read(plugins_file)); - for(var i in plugins){ - var plugin = plugins[i]; - if(plugin.match('^[a-zA-Z]+://')){ - loadIitcPlugin(plugin); - }else{ - loadLocalIitcPlugin(plugin); - } - } -} - -function s(file) { - console.log('SCREENSHOT') - page.render(file); - var startTime = new Date().getTime(); - var startTime = new Date().getTime(); - var interval = setInterval(function(){ - if(new Date().getTime() - startTime > 5000){ - clearInterval(interval); - phantom.exit(0); - return; - } - console.log('doSomeOutput') - }, 1000); -} - -function hideDebris() { - window.setTimeout(function() { - page.evaluate(function() { - if (document.querySelector('#chat')) {document.querySelector('#chat').style.display = 'none';} - if (document.querySelector('#chatcontrols')) {document.querySelector('#chatcontrols').style.display = 'none';} - if (document.querySelector('#chatinput')) {document.querySelector('#chatinput').style.display = 'none';} - if (document.querySelector('#updatestatus')) {document.querySelector('#updatestatus').style.display = 'none';} - if (document.querySelector('#sidebartoggle')) {document.querySelector('#sidebartoggle').style.display = 'none';} - if (document.querySelector('#scrollwrapper')) {document.querySelector('#scrollwrapper').style.display = 'none';} - if (document.querySelector('.leaflet-control-container')) {document.querySelector('.leaflet-control-container').style.display = 'none';} - if (document.querySelector('#portal_highlight_select')) {document.querySelector('#portal_highlight_select').style.display = 'none';} - }); - }, 200); -} - -function prepare(widthz, heightz) { - window.setTimeout(function() { - page.evaluate(function(w, h) { - var water = document.createElement('p'); - water.id='viewport-ice'; - water.style.position = 'absolute'; - water.style.top = '0'; - water.style.marginTop = '0'; - water.style.paddingTop = '0'; - water.style.left = '0'; - water.style.width = w + 'px'; - water.style.height = h + 'px'; - document.querySelectorAll('body')[0].appendChild(water); - }, widthz, heightz); - var selector = "#viewport-ice"; - setElementBounds(selector); - }, 500); -} - - -function setElementBounds(selector) { - page.clipRect = page.evaluate(function(selector) { - var clipRect = document.querySelector(selector).getBoundingClientRect(); - return { - top: clipRect.top, - left: clipRect.left, - width: clipRect.width, - height: clipRect.height - }; - }, selector); -} - -function getDateTime(format) { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth()+1; - var day = now.getDate(); - var hour = now.getHours(); - var minute = now.getMinutes(); - var second = now.getSeconds(); - var timeZone = ''; - if(month.toString().length === 1) { - month = '0' + month; - } - if(day.toString().length === 1) { - day = '0' + day; - } - if(hour.toString().length === 1) { - hour = '0' + hour; - } - if(minute.toString().length === 1) { - minute = '0' + minute; - } - if(second.toString().length === 1) { - second = '0' + second; - } - var dateTime; - if (format === 1) { - dateTime = year + '-' + month + '-' + day + '--' + hour + '-' + minute + '-' + second; - } else { - dateTime = day + '.' + month + '.' + year + ' ' + hour + ':' + minute + ':' + second + timeZone; - } - return dateTime; -} - -function addTimestamp(time) { - page.evaluate(function(dateTime, search) { - var water = document.createElement('p'); - water.id='watermark-ice'; - water.innerHTML = dateTime + ' - ' + search; - water.style.position = 'absolute'; - water.style.color = '#3A539B'; - water.style.top = '0'; - water.style.zIndex = '4404'; - water.style.marginTop = '0'; - water.style.paddingTop = '0'; - water.style.left = '0'; - water.style.fontSize = '40px'; - water.style.opacity = '0.8'; - water.style.fontFamily = 'monospace'; - water.style.textShadow = '0px 1px 8px rgba(150, 150, 150, 1)'; - document.querySelectorAll('body')[0].appendChild(water); - }, time, search); -} - -/** - * Main function. - */ -function main() { - page.evaluate(function() { - if (document.getElementById('watermark-ice')) { - var oldStamp = document.getElementById('watermark-ice'); - oldStamp.parentNode.removeChild(oldStamp); - } - }); - window.setTimeout(function() { - addTimestamp(getDateTime(0)); - file = filepath; - s(file); - }, 400); -} diff --git a/screencap_intel.js b/screencap_intel.js @@ -1,438 +0,0 @@ -var system = require('system') -var args = system.args; -var page = require('webpage').create(); -var fs = require('fs'); -var cookiespath = '.iced_cookies'; -var config = ''; -if (args.length === 1) { - console.log('Try to pass some args when invoking this script!'); -} else { - if (args.length === 5){ - var SACSID = args[1]; - var CSRF = args[2]; - var IntelURL = args[3]; - var filepath = args[4]; - var search = 'nix'; - var loginTimeout = '10000'; - }else{ - if (args.length === 6){ - var SACSID = args[1]; - var CSRF = args[2]; - var IntelURL = args[3]; - var filepath = args[4]; - var search = args[5]; - var loginTimeout = '10000'; - } - } -} - -function validateEmail(email) { - var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; - return re.test(email); -} - -function quit(err) { - phantom.exit(1); -} - -if (validateEmail(SACSID)) { - loadCookies(function() { - if (config.SACSID == undefined || config.SACSID == '') { - firePlainLogin(SACSID, CSRF); - } else { - addCookies(config.SACSID, config.CSRF); - console.log('Using cookies to log in'); - afterCookieLogin(); - } - }); -}else { - addCookies(SACSID, CSRF); - afterCookieLogin(IntelURL, search); -} - -function firePlainLogin(SACSID, CSRF) { - page.open('https://www.ingress.com/intel', function (status) { - page.evaluate(function () { - localStorage.clear() - }); - if (status !== 'success') {quit('unable to connect to remote server')} - - var link = 'https://www.google.com/accounts/ServiceLogin?service=ah&passive=true&continue=https://appengine.google.com/_ah/conflogin%3Fcontinue%3Dhttps://www.ingress.com/intel&ltmpl=' - - page.open(link, function () { - login(SACSID, CSRF); - }); - }); -} - -function loadCookies(callback) { - if(fs.exists(cookiespath)) { - var stream = fs.open(cookiespath, 'r'); - - while(!stream.atEnd()) { - var line = stream.readLine().split('='); - if(line[0] === 'SACSID') { - config.SACSID = line[1]; - } else if(line[0] === 'csrftoken') { - config.CSRF = line[1]; - } else { - config.SACSID = ''; - config.CSRF = ''; - } - } - stream.close(); - } - callback(); -} - -function isSignedIn() { - return page.evaluate(function() { - return document.getElementsByTagName('a')[0].innerText.trim() !== 'Sign in'; - }); -} - -function storeCookies() { - var cookies = page.cookies; - fs.write(cookiespath, '', 'w'); - for(var i in cookies) { - fs.write(cookiespath, cookies[i].name + '=' + cookies[i].value +'\n', 'a'); - } -} - -function login(l, p) { - if (document.querySelector('#timeoutError')){ - login(l, p) - firePlainLogin(l, p) - } - waitFor({ - timeout: 240000, - check: function () { - return page.evaluate(function() { - if (document.querySelector('#gaia_loginform')) { - return true; - }else{ - return false; - } - }); - }, - success: function () { - page.evaluate(function (l) { - document.getElementById('Email').value = l; - }, l); - page.evaluate(function () { - document.querySelector("#next").click(); - }); - window.setTimeout(function () { - page.evaluate(function (p) { - document.getElementById('Passwd').value = p; - }, p); - if(document.querySelector("#next")){ - page.evaluate(function () { - document.querySelector("#next").click(); - }); - }else{ - page.evaluate(function () { - document.querySelector("#signIn").click(); - }); - } -// page.evaluate(function () { -// document.getElementById('gaia_loginform').submit(); -// }); - window.setTimeout(function () { - if (page.url.substring(0,40) === 'https://accounts.google.com/ServiceLogin') { - quit('login failed: wrong email and/or password'); - } - - if (page.url.substring(0,40) === 'https://appengine.google.com/_ah/loginfo') { - page.evaluate(function () { - document.getElementById('persist_checkbox').checked = true; - document.getElementsByTagName('form').submit(); - }); - } - - if (page.url.substring(0,44) === 'https://accounts.google.com/signin/challenge') { - twostep = system.stdin.readLine(); - } - - // if (twostep) { - // page.evaluate(function (code) { - // document.getElementById('totpPin').value = code; - // }, twostep); - // page.evaluate(function () { - // document.getElementById('submit').click(); - // document.getElementById('challenge').submit(); - // }); - // } - window.setTimeout(afterPlainLogin(IntelURL, search), loginTimeout); - }, loginTimeout) - }, loginTimeout / 10); - }, - error: function () { - quit(); - } - }); -} - -function afterPlainLogin(IntelURL, search) { - page.open(IntelURL, function(status) { - if (status !== 'success') {quit('unable to connect to remote server')} - - if (!isSignedIn()) { - console.log('Something went wrong. Please, sign in to Google via your browser and restart ICE. Don\'t worry, your Ingress account will not be affected.'); - quit(); - } - setTimeout(function() { - storeCookies(); - waitFor({ - timeout: 240000, - check: function () { - return page.evaluate(function() { - if (document.querySelector('#percent_text').textContent.indexOf('90') != -1) { - if (!document.getElementById("loading_msg").style.display){ - return true; - }else{ - return false; - } - }else{ - return false; - } - }); - }, - success: function () { - page.evaluate(function() { - document.querySelector("#filters_container").style.display= 'none'; - }); - hideDebris(); - prepare('1920', '1080', search); - main(); - }, - error: function () { - page.evaluate(function() { - document.querySelector("#filters_container").style.display= 'none'; - }); - hideDebris(); - prepare('1920', '1080', search); - main(); - } - }); - }, "5000"); - }); -} - -function addCookies(sacsid, csrf) { - phantom.addCookie({ - name: 'SACSID', - value: sacsid, - domain: 'www.ingress.com', - path: '/', - httponly: true, - secure: true - }); - phantom.addCookie({ - name: 'csrftoken', - value: csrf, - domain: 'www.ingress.com', - path: '/' - }); -} - -function waitFor ($config) { - $config._start = $config._start || new Date(); - if ($config.timeout && new Date - $config._start > $config.timeout) { - if ($config.error) $config.error(); - if ($config.debug) console.log('timedout ' + (new Date - $config._start) + 'ms'); - return; - } - if ($config.check()) { - if ($config.debug) console.log('success ' + (new Date - $config._start) + 'ms'); - return $config.success(); - } - setTimeout(waitFor, $config.interval || 0, $config); -} - -function afterCookieLogin(IntelURL, search) { - page.open(IntelURL, function(status) { - if (status !== 'success') {quit('unable to connect to remote server')} - if(!isSignedIn()) { - if(fs.exists(cookiespath)) { - fs.remove(cookiespath); - } - if(validateEmail(SACSID)) { - page.deleteCookie('SACSID'); - page.deleteCookie('csrftoken'); - firePlainLogin(SACSID, CSRF); - return; - } else { - quit('Cookies are obsolete. Update your config file.'); - } - } - setTimeout(function() { - waitFor({ - timeout: 240000, - check: function () { - return page.evaluate(function() { - if (document.querySelector('#percent_text').textContent.indexOf('90') != -1) { - if (!document.getElementById("loading_msg").style.display){ - return true; - }else{ - return false; - } - }else{ - return false; - } - }); - }, - success: function () { - page.evaluate(function() { - document.querySelector("#filters_container").style.display= 'none'; - }); - hideDebris(); - prepare('1920', '1080', search); - main(); - }, - error: function () { - page.evaluate(function() { - document.querySelector("#filters_container").style.display= 'none'; - }); - hideDebris(); - prepare('1920', '1080', search); - main(); - } - }); - }, "5000"); - }); -} - -function s(file) { - page.render(file); - phantom.exit(0); -} - -function hideDebris() { - page.evaluate(function() { - if (document.querySelector('#comm')) {document.querySelector('#comm').style.display = 'none';} - if (document.querySelector('#player_stats')) {document.querySelector('#player_stats').style.display = 'none';} - if (document.querySelector('#game_stats')) {document.querySelector('#game_stats').style.display = 'none';} - if (document.querySelector('#geotools')) {document.querySelector('#geotools').style.display = 'none';} - if (document.querySelector('#header')) {document.querySelector('#header').style.display = 'none';} - if (document.querySelector('#snapcontrol')) {document.querySelector('#snapcontrol').style.display = 'none';} - if (document.querySelectorAll('.img_snap')[0]) {document.querySelectorAll('.img_snap')[0].style.display = 'none';} - if (document.querySelector('#display_msg_text')) {document.querySelector('#display_msg_text').style.display = 'none';} - }); - page.evaluate(function() { - var hide = document.querySelectorAll('.gmnoprint'); - for (var index = 0; index < hide.length; ++index) { - hide[index].style.display = 'none'; - } - }); -} - -function prepare(widthz, heightz, search) { - if (search == "nix") { - var selector = "#map_canvas"; - setElementBounds(selector); - }else{ - page.evaluate(function(search) { - if (document.querySelector('#geocode')){ - document.getElementById("address").value=search; - document.querySelector("input[value=Search]").click(); - } - }, search); - var selector = "#map_canvas"; - setElementBounds(selector); - } -} - -function setElementBounds(selector) { - page.clipRect = page.evaluate(function(selector) { - var clipRect = document.querySelector(selector).getBoundingClientRect(); - return { - top: clipRect.top, - left: clipRect.left, - width: clipRect.width, - height: clipRect.height - }; - }, selector); -} - -function humanPresence() { - var outside = page.evaluate(function() { - return !!(document.getElementById('butterbar') && (document.getElementById('butterbar').style.display !== 'none')); - }); - if (outside) { - var rekt = page.evaluate(function() { - return document.getElementById('butterbar').getBoundingClientRect(); - }); - page.sendEvent('click', rekt.left + rekt.width / 2, rekt.top + rekt.height / 2); - } -} - -function getDateTime(format) { - var now = new Date(); - var year = now.getFullYear(); - var month = now.getMonth()+1; - var day = now.getDate(); - var hour = now.getHours(); - var minute = now.getMinutes(); - var second = now.getSeconds(); - var timeZone = ''; - if(month.toString().length === 1) { - month = '0' + month; - } - if(day.toString().length === 1) { - day = '0' + day; - } - if(hour.toString().length === 1) { - hour = '0' + hour; - } - if(minute.toString().length === 1) { - minute = '0' + minute; - } - if(second.toString().length === 1) { - second = '0' + second; - } - var dateTime; - if (format === 1) { - dateTime = year + '-' + month + '-' + day + '--' + hour + '-' + minute + '-' + second; - } else { - dateTime = day + '.' + month + '.' + year + ' ' + hour + ':' + minute + ':' + second + timeZone; - } - return dateTime; -} - -function addTimestamp(time) { - page.evaluate(function(dateTime) { - var water = document.createElement('p'); - water.id='watermark-ice'; - water.innerHTML = dateTime; - water.style.position = 'absolute'; - water.style.color = 'orange'; - water.style.top = '0'; - water.style.left = '0'; - water.style.fontSize = '40px'; - water.style.opacity = '0.8'; - water.style.marginTop = '0'; - water.style.paddingTop = '0'; - water.style.fontFamily = 'monospace'; - water.style.textShadow = '2px 2px 5px #111717'; - document.querySelector('#map_canvas').appendChild(water); - }, time); -} - -/** - * Main function. - */ -function main() { - page.evaluate(function() { - if (document.getElementById('watermark-ice')) { - var oldStamp = document.getElementById('watermark-ice'); - oldStamp.parentNode.removeChild(oldStamp); - } - }); - humanPresence(); - window.setTimeout(function() { - addTimestamp(getDateTime(0)); - file = filepath; - s(file); - }, 5000); -}