intel-screenbot.meta

Issues/PRs archive for MTRNord/intel_screenbot
git clone git://archive.git.mtrnord.blog/MTRNord/intel-screenbot.meta.git
Log | Files | Refs

4.diff (42562B)


      1 diff --git a/__init__.py b/__init__.py
      2 index ace5c67..70cb1ff 100644
      3 --- a/__init__.py
      4 +++ b/__init__.py
      5 @@ -86,31 +86,12 @@ def _get_lines(shell_command):
      6      return p.returncode, output, True
      7  
      8  @asyncio.coroutine
      9 -def _screencap(maptype, url, filepath, filename, SACSID, CSRF, plugins, search, bot, event):
     10 +def _screencap(url, args_filepath, filepath, filename, bot, event):
     11      loop = asyncio.get_event_loop()
     12 -    logger.info("screencapping {} and saving as {}".format(url, filepath))
     13 -    if plugins is '':
     14 -        if search == False:
     15 -            command = 'phantomjs hangupsbot/plugins/intel_screenbot/screencap_' + maptype + '.js "' + SACSID + '" "' + CSRF + '" "' + url + '" "' + filepath + '"'
     16 -            task = _get_lines(command)
     17 -            task = asyncio.wait_for(task, 420.0)
     18 -            exitcode, output, status = yield from task
     19 -        else:
     20 -            command = 'phantomjs hangupsbot/plugins/intel_screenbot/screencap_' + maptype + '.js "' + SACSID + '" "' + CSRF + '" "' + url + '" "' + filepath + '" "' + search + '"'
     21 -            task = _get_lines(command)
     22 -            task = asyncio.wait_for(task, 420.0)
     23 -            exitcode, output, status = yield from task
     24 -    else:
     25 -        if search == False:
     26 -            command = 'phantomjs hangupsbot/plugins/intel_screenbot/screencap_' + maptype + '.js "' + SACSID + '" "' + CSRF + '" "' + url + '" "' + filepath + '" "' + plugins + '"'
     27 -            task = _get_lines(command)
     28 -            task = asyncio.wait_for(task, 420.0)
     29 -            exitcode, output, status = yield from task
     30 -        else:
     31 -            command = 'phantomjs hangupsbot/plugins/intel_screenbot/screencap_' + maptype + '.js "' + SACSID + '" "' + CSRF + '" "' + url + '" "' + filepath + '" "' + search + '" "' + plugins + '"'
     32 -            task = _get_lines(command)
     33 -            task = asyncio.wait_for(task, 420.0)
     34 -            exitcode, output, status = yield from task
     35 +    command = 'phantomjs hangupsbot/plugins/intel_screenbot/screencap.js "' + args_filepath + '"'
     36 +    task = _get_lines(command)
     37 +    task = asyncio.wait_for(task, 420.0)
     38 +    exitcode, output, status = yield from task
     39  
     40      # read the resulting file into a byte array
     41      # yield from asyncio.sleep(10)
     42 @@ -149,6 +130,8 @@ def intel(bot, event, *args):
     43      """get a screenshot of a search term or intel URL or the default intel URL of the hangout.
     44      """
     45  
     46 +    arguments = {}
     47 +
     48      if args:
     49          if len(args) > 1:
     50              url = ' '.join(str(i) for i in args)
     51 @@ -159,22 +142,17 @@ def intel(bot, event, *args):
     52      else:
     53          url = bot.conversation_memory_get(event.conv_id, 'IntelURL')
     54  
     55 -    if bot.config.exists(["intel_screenbot", "SACSID"]):
     56 -        if bot.config.exists(["intel_screenbot", "CSRF"]):
     57 -            SACSID = bot.config.get_by_path(["intel_screenbot", "SACSID"])
     58 -            CSRF = bot.config.get_by_path(["intel_screenbot", "CSRF"])
     59 -        else:
     60 -            html = "<i><b>{}</b> No Intel password has been added to config. Unable to authenticate".format(event.user.full_name)
     61 -            yield from bot.coro_send_message(event.conv, html)
     62 -    elif bot.config.exists(["intel_screenbot", "email"]):
     63 +    if bot.config.exists(["intel_screenbot", "email"]):
     64          if bot.config.exists(["intel_screenbot", "password"]):
     65 -            SACSID = bot.config.get_by_path(["intel_screenbot", "email"])
     66 -            CSRF = bot.config.get_by_path(["intel_screenbot", "password"])
     67 +            email = bot.config.get_by_path(["intel_screenbot", "email"])
     68 +            password = bot.config.get_by_path(["intel_screenbot", "password"])
     69 +            arguments['email'] = email
     70 +            arguments['password'] = password
     71          else:
     72              html = "<i><b>{}</b> No Intel password has been added to config. Unable to authenticate".format(event.user.full_name)
     73              yield from bot.coro_send_message(event.conv, html)
     74      else:
     75 -        html = "<i><b>{}</b> No Intel SACSID Cookie or Email/password has been added to config. Unable to authenticate".format(event.user.full_name)
     76 +        html = "<i><b>{}</b> No Intel Email/password has been added to config. Unable to authenticate".format(event.user.full_name)
     77          yield from bot.coro_send_message(event.conv, html)
     78  
     79      if url is None:
     80 @@ -182,29 +160,53 @@ def intel(bot, event, *args):
     81          yield from bot.coro_send_message(event.conv, html)
     82  
     83      else:
     84 -        if re.match(r'^[a-zA-Z]+://', url):
     85 -            search = False
     86 -            ZoomSearch = re.finditer(r"(?:&z=).*", url)
     87 -            for matchNum, zoomlevel_raw in enumerate(ZoomSearch):
     88 -                matchNum = matchNum + 1
     89 -            zoomlevel_clean = zoomlevel_raw.group()
     90 -            zoomlevel = zoomlevel_clean[3:][:2]
     91 -            if zoomlevel.isdigit():
     92 -                yield from bot.coro_send_message(event.conv_id, "<i>intel map at zoom level "+ zoomlevel + " requested, please wait...</i>")
     93 +        if re.match(r'(http(s)?:\/\/)', url):
     94 +            search = 'nix'
     95 +            zoomParameter = re.search(r"(?:&z=)", url, re.IGNORECASE)
     96 +            if zoomParameter:
     97 +                ZoomSearch = re.finditer(r"(?:&z=).*", url, flags=re.I)
     98 +                for matchNum, zoomlevel_raw in enumerate(ZoomSearch):
     99 +                    matchNum = matchNum + 1
    100 +                zoomlevel_clean = zoomlevel_raw.group()
    101 +                zoomlevel = zoomlevel_clean[3:][:2]
    102 +                if zoomlevel.isdigit():
    103 +                    yield from bot.coro_send_message(event.conv_id, "<i>intel map at zoom level "+ zoomlevel + " requested, please wait...</i>")
    104              else:
    105                  yield from bot.coro_send_message(event.conv_id, "<i>intel map at last zoom level requested, please wait...</i>")
    106          else:
    107              search = url
    108 -            logger.info(search);
    109 +            zoomParameter = re.search(r"(?<=z=)", url, re.IGNORECASE)
    110 +            if zoomParameter:
    111 +                ZoomSearch = re.finditer(r"(?<=z=)[^\s]+", url, flags=re.I)
    112 +                for matchNum, zoomlevel_raw in enumerate(ZoomSearch):
    113 +                    matchNum = matchNum + 1
    114 +                zoomlevel = zoomlevel_raw.group()
    115 +                search = search.replace("z={}".format(zoomlevel),"")
    116 +                if zoomlevel.isdigit():
    117 +                    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>")
    118 +                    arguments['zoomlevel'] = str(zoomlevel)
    119 +            else:
    120 +                yield from bot.coro_send_message(event.conv_id, "<i>intel map is searching " + search + " and screenshooting as requested, please wait...</i>")
    121              url = 'https://www.ingress.com/intel'
    122 -            yield from bot.coro_send_message(event.conv_id, "<i>intel map is searching " + search + " and screenshooting as requested, please wait...</i>")
    123  
    124          filepath = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
    125          filename = filepath.split('/', filepath.count('/'))[-1]
    126 +        args_filepath = tempfile.NamedTemporaryFile(prefix="args_{}".format(event.conv_id), suffix=".json", delete=False).name
    127          logger.debug("temporary screenshot file: {}".format(filepath))
    128 +        logger.debug("temporary args file: {}".format(args_filepath))
    129 +
    130 +        arguments['search'] = search
    131 +        arguments['url'] = url
    132 +        arguments['filepath'] = filepath
    133 +        arguments['maptype'] = "intel"
    134 +
    135 +        with open(args_filepath, 'w') as out:
    136 +            out.write(json.dumps(arguments))
    137 +
    138 +
    139          try:
    140              loop = asyncio.get_event_loop()
    141 -            image_data = yield from _screencap("intel", url, filepath, filename, SACSID, CSRF, "", search, bot, event)
    142 +            image_data = yield from _screencap(url, args_filepath, filepath, filename, bot, event)
    143          except Exception as e:
    144              yield from bot.coro_send_message(event.conv_id, "<i>error getting screenshot</i>")
    145              logger.exception("screencap failed".format(url))
    146 @@ -215,6 +217,8 @@ def iitc(bot, event, *args):
    147      """get a screenshot of a search term or intel URL or the default intel URL of the hangout.
    148      """
    149  
    150 +    arguments = {}
    151 +
    152      if args:
    153          if len(args) > 1:
    154              url = ' '.join(str(i) for i in args)
    155 @@ -225,50 +229,58 @@ def iitc(bot, event, *args):
    156      else:
    157          url = bot.conversation_memory_get(event.conv_id, 'IntelURL')
    158  
    159 -    if bot.config.exists(["intel_screenbot", "SACSID"]):
    160 -        if bot.config.exists(["intel_screenbot", "CSRF"]):
    161 -            SACSID = bot.config.get_by_path(["intel_screenbot", "SACSID"])
    162 -            CSRF = bot.config.get_by_path(["intel_screenbot", "CSRF"])
    163 -        else:
    164 -            html = "<i><b>{}</b> No Intel password has been added to config. Unable to authenticate".format(event.user.full_name)
    165 -            yield from bot.coro_send_message(event.conv, html)
    166 -    elif bot.config.exists(["intel_screenbot", "email"]):
    167 +    if bot.config.exists(["intel_screenbot", "email"]):
    168          if bot.config.exists(["intel_screenbot", "password"]):
    169 -            SACSID = bot.config.get_by_path(["intel_screenbot", "email"])
    170 -            CSRF = bot.config.get_by_path(["intel_screenbot", "password"])
    171 +            email = bot.config.get_by_path(["intel_screenbot", "email"])
    172 +            password = bot.config.get_by_path(["intel_screenbot", "password"])
    173 +            arguments['email'] = email
    174 +            arguments['password'] = password
    175          else:
    176              html = "<i><b>{}</b> No Intel password has been added to config. Unable to authenticate".format(event.user.full_name)
    177              yield from bot.coro_send_message(event.conv, html)
    178      else:
    179 -        html = "<i><b>{}</b> No Intel SACSID Cookie or Email/password has been added to config. Unable to authenticate".format(event.user.full_name)
    180 +        html = "<i><b>{}</b> No Intel Email/password has been added to config. Unable to authenticate".format(event.user.full_name)
    181          yield from bot.coro_send_message(event.conv, html)
    182 -        
    183 +
    184      if url is None:
    185          html = "<i><b>{}</b> No Intel URL has been set for screenshots.".format(event.user.full_name)
    186          yield from bot.coro_send_message(event.conv, html)
    187  
    188      else:
    189 -        if re.match(r'^[a-zA-Z]+://', url):
    190 -            search = False
    191 -            ZoomSearch = re.finditer(r"(?:&z=).*", url)
    192 -            for matchNum, zoomlevel_raw in enumerate(ZoomSearch):
    193 -                matchNum = matchNum + 1
    194 -            zoomlevel_clean = zoomlevel_raw.group()
    195 -            zoomlevel = zoomlevel_clean[3:][:2]
    196 -            if zoomlevel.isdigit():
    197 -                yield from bot.coro_send_message(event.conv_id, "<i>intel map at zoom level "+ zoomlevel + " requested, please wait...</i>")
    198 +        if re.match(r'(http(s)?:\/\/)', url):
    199 +            search = 'nix'
    200 +            zoomParameter = re.search(r"(?:&z=)", test_str, re.IGNORECASE)
    201 +            if zoomParameter:
    202 +                ZoomSearch = re.finditer(r"(?:&z=).*", url, flags=re.I)
    203 +                for matchNum, zoomlevel_raw in enumerate(ZoomSearch):
    204 +                    matchNum = matchNum + 1
    205 +                zoomlevel_clean = zoomlevel_raw.group()
    206 +                zoomlevel = zoomlevel_clean[3:][:2]
    207 +                if zoomlevel.isdigit():
    208 +                    yield from bot.coro_send_message(event.conv_id, "<i>intel map at zoom level "+ zoomlevel + " requested, please wait...</i>")
    209              else:
    210                  yield from bot.coro_send_message(event.conv_id, "<i>intel map at last zoom level requested, please wait...</i>")
    211          else:
    212              search = url
    213 -            logger.info(search);
    214 +            zoomParameter = re.search(r"(?<=z=)", url, re.IGNORECASE)
    215 +            if zoomParameter:
    216 +                ZoomSearch = re.finditer(r"(?<=z=)[^\s]+", url, flags=re.I)
    217 +                for matchNum, zoomlevel_raw in enumerate(ZoomSearch):
    218 +                    matchNum = matchNum + 1
    219 +                zoomlevel = zoomlevel_raw.group()
    220 +                search = search.replace("z={}".format(zoomlevel),"")
    221 +                if zoomlevel.isdigit():
    222 +                    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>")
    223 +                    arguments['zoomlevel'] = str(zoomlevel)
    224 +            else:
    225 +                yield from bot.coro_send_message(event.conv_id, "<i>intel map is searching " + search + " and screenshooting as requested, please wait...</i>")
    226              url = 'https://www.ingress.com/intel'
    227 -            yield from bot.coro_send_message(event.conv_id, "<i>intel map is searching " + search + " and screenshooting as requested, please wait...</i>")
    228  
    229          filepath = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name
    230          filename = filepath.split('/', filepath.count('/'))[-1]
    231 -        plugins_filepath = tempfile.NamedTemporaryFile(prefix=event.conv_id, suffix=".json", delete=False).name
    232 +        args_filepath = tempfile.NamedTemporaryFile(prefix="args_{}".format(event.conv_id), suffix=".json", delete=False).name
    233          logger.debug("temporary screenshot file: {}".format(filepath))
    234 +        logger.debug("temporary args file: {}".format(args_filepath))
    235          if bot.conversation_memory_get(event.conv_id, 'iitc_plugins'):
    236              plugins = []
    237              plugin_names = bot.conversation_memory_get(event.conv_id, 'iitc_plugins').split(", ")
    238 @@ -280,12 +292,18 @@ def iitc(bot, event, *args):
    239          else:
    240               plugins = ''
    241  
    242 -        with open(plugins_filepath, 'w') as out:
    243 -            out.write(json.dumps(plugins))
    244 +        arguments['plugins'] = plugins
    245 +        arguments['search'] = search
    246 +        arguments['url'] = url
    247 +        arguments['filepath'] = filepath
    248 +        arguments['maptype'] = "iitc"
    249 +
    250 +        with open(args_filepath, 'w') as out:
    251 +            out.write(json.dumps(arguments))
    252  
    253          try:
    254              loop = asyncio.get_event_loop()
    255 -            image_data = yield from _screencap("iitc", url, filepath, filename, SACSID, CSRF, plugins_filepath, search, bot, event)
    256 +            image_data = yield from _screencap(url, args_filepath, filepath, filename, bot, event)
    257          except Exception as e:
    258              yield from bot.coro_send_message(event.conv_id, "<i>error getting screenshot</i>")
    259              logger.exception("screencap failed".format(url))
    260 diff --git a/screencap_iitc.js b/screencap.js
    261 similarity index 72%
    262 rename from screencap_iitc.js
    263 rename to screencap.js
    264 index 6fa062a..83a260a 100644
    265 --- a/screencap_iitc.js
    266 +++ b/screencap.js
    267 @@ -4,52 +4,39 @@ var page = require('webpage').create();
    268  var fs = require('fs');
    269  var cookiespath = '.iced_cookies';
    270  var config = '';
    271 +var loginTimeout = '5000';
    272  if (args.length === 1) {
    273      console.log('Try to pass some args when invoking this script!');
    274  } else {
    275 -  if (args.length === 6){
    276 -      var SACSID  = args[1];
    277 -      var CSRF  = args[2];
    278 -      var IntelURL  = args[3];
    279 -      var filepath  = args[4];
    280 -      var plugins_file  = args[5];
    281 -      var search  = 'nix';
    282 -      var loginTimeout = '5000';
    283 -  }else{
    284 -    if (args.length === 7){
    285 -      var SACSID  = args[1];
    286 -      var CSRF  = args[2];
    287 -      var IntelURL  = args[3];
    288 -      var filepath  = args[4];
    289 -      var search  = args[5];
    290 -      var plugins_file  = args[6];
    291 -      var loginTimeout = '5000';
    292 -    }
    293 +  var arguments_file  = args[1];
    294 +  var arguments = JSON.parse(fs.read(arguments_file));
    295 +  if (arguments.hasOwnProperty('plugins')) {
    296 +    var plugins = arguments["plugins"]
    297    }
    298 +  if (arguments.hasOwnProperty('zoomlevel')) {
    299 +    var zoomlevel = arguments["zoomlevel"]
    300 +  }
    301 +  var maptype = arguments["maptype"]
    302 +  var search = arguments["search"]
    303 +  var url = arguments["url"]
    304 +  var filepath = arguments['filepath']
    305 +  var user = arguments['email']
    306 +  var pass = arguments['password']
    307  }
    308 -
    309 -function validateEmail(email) {
    310 -    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,}))$/;
    311 -    return re.test(email);
    312 -}
    313 -
    314 -function quit(err) {
    315 +function quit() {
    316    phantom.exit(0);
    317  }
    318 -if (validateEmail(SACSID)) {
    319 -  loadCookies(function() {
    320 -    if (config.SACSID == undefined || config.SACSID == '') {
    321 -      firePlainLogin(SACSID, CSRF);
    322 -    } else {
    323 -      addCookies(config.SACSID, config.CSRF);
    324 -      console.log('Using cookies to log in');
    325 -      afterCookieLogin();
    326 -    }
    327 -  });
    328 -}else {
    329 -  addCookies(SACSID, CSRF);
    330 -  afterCookieLogin(IntelURL, search);
    331 -}
    332 +
    333 +loadCookies(function() {
    334 +  if (config.SACSID == undefined || config.SACSID == '') {
    335 +    firePlainLogin(user, pass, url);
    336 +  } else {
    337 +    addCookies(config.SACSID, config.CSRF);
    338 +    console.log('Using cookies to log in');
    339 +    afterCookieLogin(url, search);
    340 +  }
    341 +});
    342 +
    343  
    344  function loadCookies(callback) {
    345    if(fs.exists(cookiespath)) {
    346 @@ -85,22 +72,21 @@ function storeCookies() {
    347    }
    348  }
    349  
    350 -function firePlainLogin(SACSID, CSRF) {
    351 +function firePlainLogin(user, pass, url) {
    352    page.open('https://www.ingress.com/intel', function (status) {
    353      page.evaluate(function () {
    354        localStorage.clear()
    355      });
    356 -    if (status !== 'success') {quit('unable to connect to remote server')}
    357 +    if (status !== 'success') {console.log("Login ERROR"); quit();}
    358      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='
    359      page.open(link, function () {
    360 -      login(SACSID, CSRF);
    361 +      login(user, pass, url);
    362      });
    363    });
    364  }
    365  
    366 -function login(l, p) {
    367 +function login(l, p, url) {
    368      if (document.querySelector('#timeoutError')){
    369 -        login(l, p)
    370          firePlainLogin(l, p)
    371      }
    372      waitFor({
    373 @@ -136,7 +122,8 @@ function login(l, p) {
    374                  }
    375                  window.setTimeout(function () {
    376                      if (page.url.substring(0,40) === 'https://accounts.google.com/ServiceLogin') {
    377 -                        quit('login failed: wrong email and/or password');
    378 +                        console.log("login failed: wrong email and/or password")
    379 +                        quit()
    380                      }
    381  
    382                      if (page.url.substring(0,40) === 'https://appengine.google.com/_ah/loginfo') {
    383 @@ -149,39 +136,49 @@ function login(l, p) {
    384                      if (page.url.substring(0,44) === 'https://accounts.google.com/signin/challenge') {
    385                          twostep = system.stdin.readLine();
    386                      }
    387 -                    window.setTimeout(afterPlainLogin(IntelURL, search), loginTimeout);
    388 +                    window.setTimeout(afterPlainLogin(url, search), loginTimeout);
    389                  }, loginTimeout)
    390              }, loginTimeout / 10);
    391          },
    392          error: function () {
    393 +            console.log("error waitingFor loginform")
    394              quit();
    395          }
    396      });
    397  }
    398  
    399 -function afterPlainLogin(IntelURL, search) {
    400 +function afterPlainLogin(url, search) {
    401    page.viewportSize = { width: '1280', height: '720' };
    402 -  page.open(IntelURL, function(status) {
    403 -    if (status !== 'success') {quit('unable to connect to remote server')}
    404 +  page.open(url, function(status) {
    405 +    console.log(url)
    406 +    if (status !== 'success') {console.log('unable to connect to remote server afterPlainLogin'); quit()}
    407      if (!isSignedIn()) {
    408        console.log("not logged in")
    409        quit();
    410      }
    411      setTimeout(function() {
    412 -		setupIITC()
    413 +      storeCookies();
    414 +		  setupIITC()
    415          setTimeout(function() {
    416 -          setTimeout(function() {if (search != "nix") {searchfunc(search);}}, 1000);
    417 +          setTimeout(function() {
    418 +            if (search != 'nix') {
    419 +              searchfunc(search);
    420 +            }
    421 +          }, 1000);
    422              waitFor({
    423                  timeout: 240000,
    424                  check: function () {
    425 -                    return page.evaluate(function() {
    426 -                        if (document.querySelector('.map').textContent.indexOf('done') != -1) {
    427 -                            return true;
    428 -                        }else{
    429 -                            console.log('generateFakeOutput')
    430 -                            return false;
    431 -                        }
    432 -                    });
    433 +                  return page.evaluate(function(zoomlevel) {
    434 +                    if (typeof zoomlevel === 'undefined' || zoomlevel === null) {
    435 +                      window.map.setZoom(zoomlevel,animate=false)
    436 +                    }
    437 +                    if (document.querySelector('.map').textContent.indexOf('done') != -1) {
    438 +                        return true;
    439 +                    }else{
    440 +                        console.log('generateFakeOutput')
    441 +                        return false;
    442 +                    }
    443 +                  }, zoomlevel);
    444                  },
    445                  success: function () {
    446                    var startTime = new Date().getTime();
    447 @@ -260,38 +257,33 @@ function loadLocalIitcPlugin(src) {
    448      page.injectJs(src)
    449  }
    450  
    451 -function afterCookieLogin(IntelURL, search) {
    452 +function afterCookieLogin(url, search) {
    453    page.viewportSize = { width: '1280', height: '720' };
    454 -  page.open(IntelURL, function(status) {
    455 +  page.open(url, function(status) {
    456      if (status !== 'success') {quit('unable to connect to remote server')}
    457      if(!isSignedIn()) {
    458        if(fs.exists(cookiespath)) {
    459          fs.remove(cookiespath);
    460        }
    461 -      if(validateEmail(SACSID)) {
    462 -        page.deleteCookie('SACSID');
    463 -        page.deleteCookie('csrftoken');
    464 -        firePlainLogin(SACSID, CSRF);
    465 -        return;
    466 -      } else {
    467 -        quit('Cookies are obsolete. Update your config file.');
    468 -      }
    469 +      quit('Cookies are obsolete. Update your config file.');
    470      }
    471      setTimeout(function() {
    472      	setupIITC()
    473          setTimeout(function() {
    474 -          if (search != "nix") {searchfunc(search);}
    475 +          if (search != "nix") {
    476 +            searchfunc(search);
    477 +          }
    478              waitFor({
    479                  timeout: 240000,
    480                  check: function () {
    481 -                    return page.evaluate(function() {
    482 -                        if (document.querySelector('.map').textContent.indexOf('done') != -1) {
    483 -                            return true;
    484 -                        }else{
    485 -                            console.log('generateFakeOutput')
    486 -                            return false;
    487 -                        }
    488 -                    });
    489 +                  return page.evaluate(function() {
    490 +                    if (document.querySelector('.map').textContent.indexOf('done') != -1) {
    491 +                        return true;
    492 +                    }else{
    493 +                        console.log('generateFakeOutput')
    494 +                        return false;
    495 +                    }
    496 +                  });
    497                  },
    498                  success: function () {
    499                    var startTime = new Date().getTime();
    500 @@ -326,7 +318,7 @@ function afterCookieLogin(IntelURL, search) {
    501  }
    502  
    503  function searchfunc(search){
    504 -  page.evaluate(function(search) {
    505 +  page.evaluate(function(search, zoomlevel) {
    506      if (document.querySelector('#search')){
    507          window.addHook('search', function(query) {
    508            var checkExist = setInterval(function() {
    509 @@ -335,18 +327,22 @@ function searchfunc(search){
    510                map.fitBounds(query.results[0].bounds, {maxZoom: 17})
    511                clearInterval(checkExist);
    512              }
    513 +            if (typeof zoomlevel !== 'undefined' || zoomlevel !== null) {
    514 +              console.log(zoomlevel)
    515 +              window.map.setZoom(zoomlevel,animate=false)
    516 +            }
    517            }, 100);
    518          });
    519        setTimeout(function() {
    520          window.search.doSearch(search, true)
    521        }, 2000);
    522      }
    523 -  }, search);
    524 +  }, search, zoomlevel);
    525  }
    526  
    527  function setupIITC(){
    528      loadIitcPlugin('https://static.iitc.me/build/release/plugins/canvas-render.user.js');
    529 -    page.evaluate(function() {
    530 +    page.evaluate(function(maptype) {
    531          localStorage['ingress.intelmap.layergroupdisplayed'] = JSON.stringify({
    532            "Unclaimed Portals": true,
    533            "Level 1 Portals": true,
    534 @@ -369,16 +365,22 @@ function setupIITC(){
    535          script.type='text/javascript';
    536          script.src='https://static.iitc.me/build/test/total-conversion-build.user.js';
    537          document.head.insertBefore(script, document.head.lastChild);
    538 -    	localStorage['iitc-base-map'] = 'Google Roads';
    539 -    });
    540 -    var plugins = JSON.parse(fs.read(plugins_file));
    541 -    for(var i in plugins){
    542 -        var plugin = plugins[i];
    543 -        if(plugin.match('^[a-zA-Z]+://')){
    544 -            loadIitcPlugin(plugin);
    545 -        }else{
    546 -           loadLocalIitcPlugin(plugin);
    547 +        if (maptype == "intel") {
    548 +          localStorage['iitc-base-map'] = 'Google Default Ingress Map';
    549 +        }else {
    550 +          localStorage['iitc-base-map'] = 'Google Roads';
    551          }
    552 +    }, maptype);
    553 +    if (maptype != "intel") {
    554 +      console.log(plugins);
    555 +      for(var i in plugins){
    556 +          var plugin = plugins[i];
    557 +          if(plugin.match('(http(s)?:\/\/)')){
    558 +              loadIitcPlugin(plugin);
    559 +          }else{
    560 +             loadLocalIitcPlugin(plugin);
    561 +          }
    562 +      }
    563      }
    564  }
    565  
    566 @@ -390,7 +392,7 @@ function s(file) {
    567    var interval = setInterval(function(){
    568      if(new Date().getTime() - startTime > 5000){
    569        clearInterval(interval);
    570 -      phantom.exit(0);
    571 +      quit();
    572        return;
    573      }
    574      console.log('doSomeOutput')
    575 @@ -478,23 +480,43 @@ function getDateTime(format) {
    576  }
    577  
    578  function addTimestamp(time) {
    579 -  page.evaluate(function(dateTime, search) {
    580 -    var water = document.createElement('p');
    581 -    water.id='watermark-ice';
    582 -    water.innerHTML = dateTime + ' - ' + search;
    583 -    water.style.position = 'absolute';
    584 -    water.style.color = '#3A539B';
    585 -    water.style.top = '0';
    586 -    water.style.zIndex = '4404';
    587 -    water.style.marginTop = '0';
    588 -    water.style.paddingTop = '0';
    589 -    water.style.left = '0';
    590 -    water.style.fontSize = '40px';
    591 -    water.style.opacity = '0.8';
    592 -    water.style.fontFamily = 'monospace';
    593 -    water.style.textShadow = '0px 1px 8px rgba(150, 150, 150, 1)';
    594 -    document.querySelectorAll('body')[0].appendChild(water);
    595 -  }, time, search);
    596 +  if (maptype == "iitc") {
    597 +    page.evaluate(function(dateTime, search) {
    598 +      var water = document.createElement('p');
    599 +      water.id='watermark-ice';
    600 +      water.innerHTML = dateTime + ' - ' + search;
    601 +      water.style.position = 'absolute';
    602 +      water.style.color = '#3A539B';
    603 +      water.style.top = '0';
    604 +      water.style.zIndex = '4404';
    605 +      water.style.marginTop = '0';
    606 +      water.style.paddingTop = '0';
    607 +      water.style.left = '0';
    608 +      water.style.fontSize = '40px';
    609 +      water.style.opacity = '0.8';
    610 +      water.style.fontFamily = 'monospace';
    611 +      water.style.textShadow = '0px 1px 8px rgba(150, 150, 150, 1)';
    612 +      document.querySelectorAll('body')[0].appendChild(water);
    613 +    }, time, search);
    614 +  }else {
    615 +    page.evaluate(function(dateTime, search) {
    616 +      var water = document.createElement('p');
    617 +      water.id='watermark-ice';
    618 +      water.style.zIndex = '4404';
    619 +      water.innerHTML = dateTime + ' - ' + search;
    620 +      water.style.position = 'absolute';
    621 +      water.style.color = 'orange';
    622 +      water.style.top = '0';
    623 +      water.style.left = '0';
    624 +      water.style.fontSize = '40px';
    625 +      water.style.opacity = '0.8';
    626 +      water.style.marginTop = '0';
    627 +      water.style.paddingTop = '0';
    628 +      water.style.fontFamily = 'monospace';
    629 +      water.style.textShadow = '0px 1px 8px rgba(150, 150, 150, 1)';
    630 +      document.querySelectorAll('body')[0].appendChild(water);
    631 +    }, time, search);
    632 +  }
    633  }
    634  
    635  /**
    636 diff --git a/screencap_intel.js b/screencap_intel.js
    637 deleted file mode 100644
    638 index 0696c0e..0000000
    639 --- a/screencap_intel.js
    640 +++ /dev/null
    641 @@ -1,438 +0,0 @@
    642 -var system = require('system')
    643 -var args = system.args;
    644 -var page = require('webpage').create();
    645 -var fs = require('fs');
    646 -var cookiespath = '.iced_cookies';
    647 -var config = '';
    648 -if (args.length === 1) {
    649 -    console.log('Try to pass some args when invoking this script!');
    650 -} else {
    651 -  if (args.length === 5){
    652 -      var SACSID  = args[1];
    653 -      var CSRF  = args[2];
    654 -      var IntelURL  = args[3];
    655 -      var filepath  = args[4];
    656 -      var search  = 'nix';
    657 -      var loginTimeout = '10000';
    658 -  }else{
    659 -    if (args.length === 6){
    660 -      var SACSID  = args[1];
    661 -      var CSRF  = args[2];
    662 -      var IntelURL  = args[3];
    663 -      var filepath  = args[4];
    664 -      var search  = args[5];
    665 -      var loginTimeout = '10000';
    666 -    }
    667 -  }
    668 -}
    669 -
    670 -function validateEmail(email) {
    671 -    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,}))$/;
    672 -    return re.test(email);
    673 -}
    674 -
    675 -function quit(err) {
    676 -  phantom.exit(1);
    677 -}
    678 -
    679 -if (validateEmail(SACSID)) {
    680 -  loadCookies(function() {
    681 -    if (config.SACSID == undefined || config.SACSID == '') {
    682 -      firePlainLogin(SACSID, CSRF);
    683 -    } else {
    684 -      addCookies(config.SACSID, config.CSRF);
    685 -      console.log('Using cookies to log in');
    686 -      afterCookieLogin();
    687 -    }
    688 -  });
    689 -}else {
    690 -  addCookies(SACSID, CSRF);
    691 -  afterCookieLogin(IntelURL, search);
    692 -}
    693 -
    694 -function firePlainLogin(SACSID, CSRF) {
    695 -  page.open('https://www.ingress.com/intel', function (status) {
    696 -    page.evaluate(function () {
    697 -      localStorage.clear()
    698 -    });
    699 -    if (status !== 'success') {quit('unable to connect to remote server')}
    700 -
    701 -    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='
    702 -
    703 -    page.open(link, function () {
    704 -      login(SACSID, CSRF);
    705 -    });
    706 -  });
    707 -}
    708 -
    709 -function loadCookies(callback) {
    710 -  if(fs.exists(cookiespath)) {
    711 -    var stream = fs.open(cookiespath, 'r');
    712 -
    713 -    while(!stream.atEnd()) {
    714 -      var line = stream.readLine().split('=');
    715 -      if(line[0] === 'SACSID') {
    716 -        config.SACSID = line[1];
    717 -      } else if(line[0] === 'csrftoken') {
    718 -        config.CSRF = line[1];
    719 -      } else {
    720 -        config.SACSID = '';
    721 -        config.CSRF = '';
    722 -      }
    723 -    }
    724 -    stream.close();
    725 -  }
    726 -  callback();
    727 -}
    728 -
    729 -function isSignedIn() {
    730 -  return page.evaluate(function() {
    731 -    return document.getElementsByTagName('a')[0].innerText.trim() !== 'Sign in';
    732 -  });
    733 -}
    734 -
    735 -function storeCookies() {
    736 -  var cookies = page.cookies;
    737 -  fs.write(cookiespath, '', 'w');
    738 -  for(var i in cookies) {
    739 -    fs.write(cookiespath, cookies[i].name + '=' + cookies[i].value +'\n', 'a');
    740 -  }
    741 -}
    742 -
    743 -function login(l, p) {
    744 -    if (document.querySelector('#timeoutError')){
    745 -        login(l, p)
    746 -        firePlainLogin(l, p)
    747 -    }
    748 -    waitFor({
    749 -        timeout: 240000,
    750 -        check: function () {
    751 -            return page.evaluate(function() {
    752 -                if (document.querySelector('#gaia_loginform')) {
    753 -                    return true;
    754 -                }else{
    755 -                    return false;
    756 -                }
    757 -            });
    758 -        },
    759 -        success: function () {
    760 -            page.evaluate(function (l) {
    761 -                document.getElementById('Email').value = l;
    762 -            }, l);
    763 -            page.evaluate(function () {
    764 -                document.querySelector("#next").click();
    765 -            });
    766 -            window.setTimeout(function () {
    767 -                page.evaluate(function (p) {
    768 -                    document.getElementById('Passwd').value = p;
    769 -                }, p);
    770 -                if(document.querySelector("#next")){
    771 -                    page.evaluate(function () {
    772 -                        document.querySelector("#next").click();
    773 -                    });
    774 -                }else{
    775 -                    page.evaluate(function () {
    776 -                        document.querySelector("#signIn").click();
    777 -                    });
    778 -                }
    779 -//                 page.evaluate(function () {
    780 -//                     document.getElementById('gaia_loginform').submit();
    781 -//                 });
    782 -                window.setTimeout(function () {
    783 -                    if (page.url.substring(0,40) === 'https://accounts.google.com/ServiceLogin') {
    784 -                        quit('login failed: wrong email and/or password');
    785 -                    }
    786 -
    787 -                    if (page.url.substring(0,40) === 'https://appengine.google.com/_ah/loginfo') {
    788 -                        page.evaluate(function () {
    789 -                            document.getElementById('persist_checkbox').checked = true;
    790 -                            document.getElementsByTagName('form').submit();
    791 -                        });
    792 -                    }
    793 -
    794 -                    if (page.url.substring(0,44) === 'https://accounts.google.com/signin/challenge') {
    795 -                        twostep = system.stdin.readLine();
    796 -                    }
    797 -
    798 -                    //       if (twostep) {
    799 -                    //         page.evaluate(function (code) {
    800 -                    //           document.getElementById('totpPin').value = code;
    801 -                    //         }, twostep);
    802 -                    //         page.evaluate(function () {
    803 -                    //           document.getElementById('submit').click();
    804 -                    //           document.getElementById('challenge').submit();
    805 -                    //         });
    806 -                    //       }
    807 -                    window.setTimeout(afterPlainLogin(IntelURL, search), loginTimeout);
    808 -                }, loginTimeout)
    809 -            }, loginTimeout / 10);
    810 -        },
    811 -        error: function () {
    812 -            quit();
    813 -        }
    814 -    });
    815 -}
    816 -
    817 -function afterPlainLogin(IntelURL, search) {
    818 -  page.open(IntelURL, function(status) {
    819 -    if (status !== 'success') {quit('unable to connect to remote server')}
    820 -
    821 -    if (!isSignedIn()) {
    822 -      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.');
    823 -      quit();
    824 -    }
    825 -    setTimeout(function() {
    826 -        storeCookies();
    827 -        waitFor({
    828 -            timeout: 240000,
    829 -            check: function () {
    830 -                return page.evaluate(function() {
    831 -                    if (document.querySelector('#percent_text').textContent.indexOf('90') != -1) {
    832 -                        if (!document.getElementById("loading_msg").style.display){
    833 -                            return true;
    834 -                        }else{
    835 -                            return false;
    836 -                        }
    837 -                    }else{
    838 -                        return false;
    839 -                    }
    840 -                });
    841 -            },
    842 -            success: function () {
    843 -                page.evaluate(function() {
    844 -                    document.querySelector("#filters_container").style.display= 'none';
    845 -                });
    846 -                hideDebris();
    847 -                prepare('1920', '1080', search);
    848 -                main();
    849 -            },
    850 -            error: function () {
    851 -                page.evaluate(function() {
    852 -                    document.querySelector("#filters_container").style.display= 'none';
    853 -                });
    854 -                hideDebris();
    855 -                prepare('1920', '1080', search);
    856 -                main();
    857 -            }
    858 -        });
    859 -    }, "5000");
    860 -  });
    861 -}
    862 -
    863 -function addCookies(sacsid, csrf) {
    864 -  phantom.addCookie({
    865 -    name: 'SACSID',
    866 -    value: sacsid,
    867 -    domain: 'www.ingress.com',
    868 -    path: '/',
    869 -    httponly: true,
    870 -    secure: true
    871 -  });
    872 -  phantom.addCookie({
    873 -    name: 'csrftoken',
    874 -    value: csrf,
    875 -    domain: 'www.ingress.com',
    876 -    path: '/'
    877 -  });
    878 -}
    879 -
    880 -function waitFor ($config) {
    881 -    $config._start = $config._start || new Date();
    882 -    if ($config.timeout && new Date - $config._start > $config.timeout) {
    883 -        if ($config.error) $config.error();
    884 -        if ($config.debug) console.log('timedout ' + (new Date - $config._start) + 'ms');
    885 -        return;
    886 -    }
    887 -    if ($config.check()) {
    888 -        if ($config.debug) console.log('success ' + (new Date - $config._start) + 'ms');
    889 -        return $config.success();
    890 -    }
    891 -    setTimeout(waitFor, $config.interval || 0, $config);
    892 -}
    893 -
    894 -function afterCookieLogin(IntelURL, search) {
    895 -  page.open(IntelURL, function(status) {
    896 -    if (status !== 'success') {quit('unable to connect to remote server')}
    897 -    if(!isSignedIn()) {
    898 -      if(fs.exists(cookiespath)) {
    899 -        fs.remove(cookiespath);
    900 -      }
    901 -      if(validateEmail(SACSID)) {
    902 -        page.deleteCookie('SACSID');
    903 -        page.deleteCookie('csrftoken');
    904 -        firePlainLogin(SACSID, CSRF);
    905 -        return;
    906 -      } else {
    907 -        quit('Cookies are obsolete. Update your config file.');
    908 -      }
    909 -    }
    910 -    setTimeout(function() {
    911 -        waitFor({
    912 -            timeout: 240000,
    913 -            check: function () {
    914 -                return page.evaluate(function() {
    915 -                    if (document.querySelector('#percent_text').textContent.indexOf('90') != -1) {
    916 -                        if (!document.getElementById("loading_msg").style.display){
    917 -                            return true;
    918 -                        }else{
    919 -                            return false;
    920 -                        }
    921 -                    }else{
    922 -                        return false;
    923 -                    }
    924 -                });
    925 -            },
    926 -            success: function () {
    927 -                page.evaluate(function() {
    928 -                    document.querySelector("#filters_container").style.display= 'none';
    929 -                });
    930 -                hideDebris();
    931 -                prepare('1920', '1080', search);
    932 -                main();
    933 -            },
    934 -            error: function () {
    935 -                page.evaluate(function() {
    936 -                    document.querySelector("#filters_container").style.display= 'none';
    937 -                });
    938 -                hideDebris();
    939 -                prepare('1920', '1080', search);
    940 -                main();
    941 -            }
    942 -        });
    943 -    }, "5000");
    944 -  });
    945 -}
    946 -
    947 -function s(file) {
    948 -  page.render(file);
    949 -  phantom.exit(0);
    950 -}
    951 -
    952 -function hideDebris() {
    953 -  page.evaluate(function() {
    954 -    if (document.querySelector('#comm'))             {document.querySelector('#comm').style.display = 'none';}
    955 -    if (document.querySelector('#player_stats'))     {document.querySelector('#player_stats').style.display = 'none';}
    956 -    if (document.querySelector('#game_stats'))       {document.querySelector('#game_stats').style.display = 'none';}
    957 -    if (document.querySelector('#geotools'))         {document.querySelector('#geotools').style.display = 'none';}
    958 -    if (document.querySelector('#header'))           {document.querySelector('#header').style.display = 'none';}
    959 -    if (document.querySelector('#snapcontrol'))      {document.querySelector('#snapcontrol').style.display = 'none';}
    960 -    if (document.querySelectorAll('.img_snap')[0])   {document.querySelectorAll('.img_snap')[0].style.display = 'none';}
    961 -    if (document.querySelector('#display_msg_text')) {document.querySelector('#display_msg_text').style.display = 'none';}
    962 -  });
    963 -  page.evaluate(function() {
    964 -    var hide = document.querySelectorAll('.gmnoprint');
    965 -    for (var index = 0; index < hide.length; ++index) {
    966 -      hide[index].style.display = 'none';
    967 -    }
    968 -  });
    969 -}
    970 -
    971 -function prepare(widthz, heightz, search) {
    972 -  if (search == "nix") {
    973 -    var selector = "#map_canvas";
    974 -    setElementBounds(selector);
    975 -  }else{
    976 -    page.evaluate(function(search) {
    977 -      if (document.querySelector('#geocode')){
    978 -        document.getElementById("address").value=search;
    979 -        document.querySelector("input[value=Search]").click();
    980 -      }
    981 -    }, search);
    982 -    var selector = "#map_canvas";
    983 -    setElementBounds(selector);
    984 -  }
    985 -}
    986 -
    987 -function setElementBounds(selector) {
    988 -  page.clipRect = page.evaluate(function(selector) {
    989 -    var clipRect = document.querySelector(selector).getBoundingClientRect();
    990 -    return {
    991 -      top:    clipRect.top,
    992 -      left:   clipRect.left,
    993 -      width:  clipRect.width,
    994 -      height: clipRect.height
    995 -    };
    996 -  }, selector);
    997 -}
    998 -
    999 -function humanPresence() {
   1000 -  var outside = page.evaluate(function() {
   1001 -    return !!(document.getElementById('butterbar') && (document.getElementById('butterbar').style.display !== 'none'));
   1002 -  });
   1003 -  if (outside) {
   1004 -    var rekt = page.evaluate(function() {
   1005 -      return document.getElementById('butterbar').getBoundingClientRect();
   1006 -    });
   1007 -    page.sendEvent('click', rekt.left + rekt.width / 2, rekt.top + rekt.height / 2);
   1008 -  }
   1009 -}
   1010 -
   1011 -function getDateTime(format) {
   1012 -  var now     = new Date();
   1013 -  var year    = now.getFullYear();
   1014 -  var month   = now.getMonth()+1;
   1015 -  var day     = now.getDate();
   1016 -  var hour    = now.getHours();
   1017 -  var minute  = now.getMinutes();
   1018 -  var second  = now.getSeconds();
   1019 -  var timeZone = '';
   1020 -  if(month.toString().length === 1) {
   1021 -    month = '0' + month;
   1022 -  }
   1023 -  if(day.toString().length === 1) {
   1024 -    day = '0' + day;
   1025 -  }
   1026 -  if(hour.toString().length === 1) {
   1027 -    hour = '0' + hour;
   1028 -  }
   1029 -  if(minute.toString().length === 1) {
   1030 -    minute = '0' + minute;
   1031 -  }
   1032 -  if(second.toString().length === 1) {
   1033 -    second = '0' + second;
   1034 -  }
   1035 -  var dateTime;
   1036 -  if (format === 1) {
   1037 -    dateTime = year + '-' + month + '-' + day + '--' + hour + '-' + minute + '-' + second;
   1038 -  } else {
   1039 -    dateTime = day + '.' + month + '.' + year + ' ' + hour + ':' + minute + ':' + second + timeZone;
   1040 -  }
   1041 -  return dateTime;
   1042 -}
   1043 -
   1044 -function addTimestamp(time) {
   1045 -  page.evaluate(function(dateTime) {
   1046 -    var water = document.createElement('p');
   1047 -    water.id='watermark-ice';
   1048 -    water.innerHTML = dateTime;
   1049 -    water.style.position = 'absolute';
   1050 -    water.style.color = 'orange';
   1051 -    water.style.top = '0';
   1052 -    water.style.left = '0';
   1053 -    water.style.fontSize = '40px';
   1054 -    water.style.opacity = '0.8';
   1055 -    water.style.marginTop = '0';
   1056 -    water.style.paddingTop = '0';
   1057 -    water.style.fontFamily = 'monospace';
   1058 -    water.style.textShadow = '2px 2px 5px #111717';
   1059 -    document.querySelector('#map_canvas').appendChild(water);
   1060 -  }, time);
   1061 -}
   1062 -
   1063 -/**
   1064 - * Main function.
   1065 - */
   1066 -function main() {
   1067 -  page.evaluate(function() {
   1068 -    if (document.getElementById('watermark-ice')) {
   1069 -      var oldStamp = document.getElementById('watermark-ice');
   1070 -      oldStamp.parentNode.removeChild(oldStamp);
   1071 -    }
   1072 -  });
   1073 -  humanPresence();
   1074 -  window.setTimeout(function() {
   1075 -    addTimestamp(getDateTime(0));
   1076 -    file = filepath;
   1077 -    s(file);
   1078 -  }, 5000);
   1079 -}