def set_location(): print try: print "You can set your location to a city (if it's in the database) or from latitude & longitude." city = raw_input("Enter city to set location to (or leave blank to skip): ") while city != "" and not city.isspace(): if location.set_location_city(city): return True city = raw_input("Enter city to set location to (or leave blank to skip): ") while True: try: print "Enter your coordinates (you can find them on Wikipedia):" latitude = float(raw_input("Enter your latitude (as a decimal number): ")) longitude = float(raw_input("Enter your longitude (as a decimal number): ")) location.set_location(latitude, longitude) return True except ValueError: print "Please enter a number (example: 45.60)" pass except IOError: return False except IOError: return False
def test_loc_objloc(self): loc = Template('Object location') loc.add(1, "one") set_location(self.tree, None) set_object_location(self.tree, loc) # Might be better without the spurious newline, but this will do. self.assertEqual( str(self.tree), """ == {{int:filedesc}} == {{Information |description={{en|1=Street Waste Bin Waste bin on the street outside Crosby and Blundellsands Station}} |date=2010-04-11 |source=From [http://www.geograph.org.uk/photo/1801330 geograph.org.uk] |author=[http://www.geograph.org.uk/profile/46411 Paul Glover] |permission= |other_versions= }} {{Object location|one}} == {{int:license-header}} == {{Geograph|1801330|Paul Glover}} [[Category:Streets in Sefton]] [[Category:Geograph images in Merseyside]] """)
def start_private_show(access_token,ltype,loc): location.set_location(loc) print '[+] Token:',access_token[:40]+'...' prot1=logic.gen_first_data(access_token,ltype) local_ses=api.get_rpc_server(access_token,prot1) new_rcp_point='https://%s/rpc'%(local_ses.rpc_server,) work_stop(local_ses,new_rcp_point)
def start_private_show(access_token, ltype, loc): location.set_location(loc) print '[+] Token:', access_token[:40] + '...' prot1 = logic.gen_first_data(access_token, ltype) local_ses = api.get_rpc_server(access_token, prot1) new_rcp_point = 'https://%s/rpc' % (local_ses.rpc_server, ) while (True): work_stop(local_ses, new_rcp_point)
def start(): global argsStored while True: if accessToken is None or globalltype is None: refresh_access() location.set_location(argsStored.location) print '[+] Token:', accessToken[:40] + '...' prot1 = logic.gen_first_data(accessToken, globalltype) local_ses = api.get_rpc_server(accessToken, prot1) new_rcp_point = 'https://%s/rpc' % (local_ses.rpc_server,) work_stop(local_ses, new_rcp_point)
def start_private_show(access_token,ltype,loc): location.set_location(loc) print '[+] Token:',access_token[:40]+'...' prot1=logic.gen_first_data(access_token,ltype) local_ses=api.get_rpc_server(access_token,prot1) new_rcp_point='https://%s/rpc'%(local_ses.rpc_server,) while(True): proto_all=logic.all_stops(local_ses) api.use_api(new_rcp_point,proto_all) #walk_circle(120) walk_random() time.sleep(2) work_stop(local_ses,new_rcp_point)
def start_private_show(access_token,ltype,loc): #try: location.set_location(loc) print '[+] Token:',access_token[:40]+'...' prot1=logic.gen_first_data(access_token,ltype) local_ses=api.get_rpc_server(access_token,prot1) try: new_rcp_point='https://%s/rpc'%(local_ses.rpc_server,) except: print '[-] rpc bad' start_private_show(access_token,ltype,loc) #while(True): work_stop(local_ses,new_rcp_point)
def start_private_show(access_token, ltype, loc): #try: location.set_location(loc) print '[+] Token:', access_token[:40] + '...' prot1 = logic.gen_first_data(access_token, ltype) local_ses = api.get_rpc_server(access_token, prot1) try: new_rcp_point = 'https://%s/rpc' % (local_ses.rpc_server, ) except: print '[-] rpc bad' start_private_show(access_token, ltype, loc) if try_item: work_stop(local_ses, new_rcp_point) else: while (True): work_stop(local_ses, new_rcp_point)
def start_private_show(access_token,ltype,loc): location.set_location(getLocation()) print '[+] Token:',access_token[:40]+'...' prot1=logic.gen_first_data(access_token,ltype) local_ses=api.get_rpc_server(access_token,prot1) new_rcp_point='https://%s/rpc'%(local_ses.rpc_server,) global lT global locat global aT aT = access_token lT = ltype locat = loc while(Success): work_stop(local_ses,new_rcp_point)
def stoplist(request): """ Returns a List of possible Stops which fit to the given name e.g. http://127.0.0.1:8000/api/stopList/?query=hauptbahnhof :param request: :return: a json """ initSession(request) if request.method == 'GET': if "query" not in request.GET: return JSONResponse({'error': "qurey not found"}, status=400) if "longitude" not in request.GET: return JSONResponse({'error': "longitude not found"}, status=400) if "latitude" not in request.GET: return JSONResponse({'error': "latitude not found"}, status=400) query = codecs.encode(request.GET["query"], 'utf-8') longitude = codecs.encode(request.GET["longitude"], 'utf-8') if float(longitude) < 0: longitude = str(360 + float(longitude)) latitude = codecs.encode(request.GET["latitude"], 'utf-8') if float(latitude) < 0: latitude = str(360 + float(latitude)) c = Controller(request.session) # Sets the location of the user for further requests loc.set_location(request, Coord(latitude, longitude)) stoplist = c.get_stoplist(query, [longitude, latitude]) if type(stoplist) == int: return JSONResponse({'error': "There was an error on search: " + str(stoplist)}, status=400) serializer = Efa_stop_list_serializer(stoplist) json = { 'query': query, 'suggestions': serializer.data } return JSONResponse(json) elif request.method == 'POST': return JSONResponse({'error': "only get request supported"}, status=400)
def route(request): """ Searches for the best Routes including walking and returns it as json Example: http://127.0.0.1:8000/api/route/?latitude=48.35882&longitude=10.90529&stopid=2000100 """ initSession(request) if request.method == 'GET': if "stopid" not in request.GET: return JSONResponse({'error': "stopid not found"}, status=400) if "longitude" not in request.GET: return JSONResponse({'error': "longitude not found"}, status=400) if "latitude" not in request.GET: return JSONResponse({'error': "latitude not found"}, status=400) stopid = codecs.encode(request.GET["stopid"], 'utf-8') longitude = codecs.encode(request.GET["longitude"], 'utf-8') latitude = codecs.encode(request.GET["latitude"], 'utf-8') if float(longitude) < 0: longitude = str(360 + float(longitude)) if float(latitude) < 0: latitude = str(360 + float(latitude)) loc.set_location(request, Coord(latitude, longitude)) c = Controller(request.session) # Here we do the search for the optimized Route routes = c.get_optimized_routes([longitude, latitude], stopid) if type(routes) == int: return JSONResponse({'error': "There was an error on search: " + str(routes)}, status=400) serializer = RouteListSerializer(RouteList(routes)) return JSONResponse({ 'stopid': stopid, 'longitude': longitude, 'latitude': latitude, 'data': serializer.data }) elif request.method == 'POST': return JSONResponse({'error': "only get request supported"}, status=400)
def main(): settings.init() parser = argparse.ArgumentParser() # If config file exists, load variables from json load = {} if os.path.isfile(CONFIG): with open(CONFIG) as data: load.update(json.load(data)) # Read passed in Arguments required = lambda x: not x in load parser.add_argument("-a", "--auth_service", help="Auth Service", required=required("auth_service")) parser.add_argument("-u", "--username", help="Username", required=required("username")) parser.add_argument("-p", "--password", help="Password", required=required("password")) parser.add_argument("-l", "--location", help="Location", required=required("location")) parser.add_argument("-d", "--debug", help="Debug Mode", action='store_true') parser.add_argument("-s", "--client_secret", help="PTC Client Secret") parser.set_defaults(DEBUG=True) args = parser.parse_args() # Passed in arguments shoud trump for key in args.__dict__: if key in load and args.__dict__[key] == None: args.__dict__[key] = load[key] # Or # args.__dict__.update({key:load[key] for key in load if args.__dict__[key] == None and key in load}) if args.auth_service not in ['ptc', 'google']: print('[!] Invalid Auth service specified') return if args.debug: settings.debug = True print('[!] DEBUG mode on') if args.client_secret is not None: global PTC_CLIENT_SECRET PTC_CLIENT_SECRET = args.client_secret set_location(args.location) if args.auth_service == 'ptc': access_token = login_ptc(args.username, args.password) else: access_token = login_google(args.username, args.password) if access_token is None: print('[-] Wrong username/password') return print('[+] RPC Session Token: {} ...'.format(access_token[:25])) api_endpoint = get_api_endpoint(args.auth_service, access_token) if api_endpoint is None: print('[-] RPC server offline') return print('[+] Received API endpoint: {}'.format(api_endpoint)) profile = get_profile(args.auth_service, api_endpoint, access_token) if profile is not None: print('[+] Login successful') profile = profile.payload[0].profile print('[+] Username: {}'.format(profile.username)) creation_time = datetime.fromtimestamp(int(profile.creation_time)/1000) print('[+] You are playing Pokemon Go since: {}'.format( creation_time.strftime('%Y-%m-%d %H:%M:%S'), )) print('[+] Poke Storage: {}'.format(profile.poke_storage)) print('[+] Item Storage: {}'.format(profile.item_storage)) for curr in profile.currency: print('[+] {}: {}'.format(curr.type, curr.amount)) else: print('[-] Ooops...')
def test_loc(self): loc = Template('Location') loc.add(1, "one") set_location(self.tree, loc) self.assertEqual(str(self.tree), "{{Location|one}}\n{{object location}}")
def process_page(self, page): location_added = False location_replaced = False location_removed = False location_was_mine = False object_location_added = False creditline_added = False revid = page.latest_revision_id tree = mwparserfromhell.parse(page.text) gridimage_id = get_gridimage_id(tree) c = geodb.cursor() c.execute( """ SELECT * FROM gridimage_base NATURAL JOIN gridimage_geo NATURAL JOIN gridimage_extra WHERE gridimage_id = ? """, (gridimage_id, )) row = c.fetchone() if row == None: raise NotInGeographDatabase("Geograph ID %d not in database" % (gridimage_id, )) try: location_template = get_location(tree) except IndexError: location_template = None new_location = location_from_row(row) minor = True bot.log("Existing location: %s" % (location_template, )) if (location_template != None and location_template.name == 'Location dec' and self.is_original_location(page, location_template) and self.is_geographbot_upload(page) and new_location != location_template): bot.log("Proposed location: %s" % (new_location, )) if (new_location != None and new_location.get('prec').value != '1000'): set_location(tree, new_location) azon, azno, distance = (az_dist_between_locations( location_template, new_location)) bot.log("Distance moved: %.1f m" % (distance, )) if distance > float(str(new_location.get('prec').value)): minor = False location_replaced = True else: set_location(tree, None) minor = False location_removed = True if (new_location != None and location_template == new_location and new_location.get('prec').value == '1000'): set_location(tree, None) minor = False location_removed = True location_was_mine = True if (location_template == None and new_location != None and new_location.get('prec').value != '1000'): set_location(tree, new_location) minor = False location_added = True bot.log("New camera location: %s" % (new_location, )) if not has_object_location(tree): objloc = object_location_from_row(row) if (objloc.get('prec').value == '1000' and not (location_removed or location_template == None)): bot.log("Skipping object location: precision is 1km") else: bot.log("New object location: %s" % (objloc, )) set_object_location(tree, objloc) minor = False object_location_added = True creditline = creditline_from_row(row) if (can_add_creditline(tree, creditline) and (self.unmodified_on_geograph_since_upload(page, row) or self.is_original_title(page, row['title']))): add_creditline(tree, creditline) creditline_added = True minor = False else: bot.log("Cannot add credit line") newtext = str(tree) if newtext != page.text: if location_replaced: if object_location_added: summary = ( "Replace dubious [[User:GeographBot|GeographBot]]-" "sourced camera location (moved %.1f m %s) and " "add object location, both from Geograph (%s)" % (distance, format_direction(azon), format_row(row))) else: summary = ( "Replace dubious [[User:GeographBot|GeographBot]]-" "sourced camera location (moved %.1f m %s), " "from Geograph (%s)" % (distance, format_direction(azon), format_row(row))) elif location_removed: if location_was_mine: summary = ( "Remove vague camera location (probably added by me)") else: summary = ( "Remove dubious [[User:GeographBot|GeographBot]]-" "sourced camera location") if object_location_added: summary += (" and add object location from Geograph (%s)" % (format_row(row), )) elif location_added: if object_location_added: summary = ( "Add camera and object locations from Geograph (%s)" % (format_row(row), )) else: summary = ("Add camera location from Geograph (%s)" % (format_row(row), )) elif object_location_added: summary = ("Add object location from Geograph (%s)" % (format_row(row), )) else: summary = "" if creditline_added: if summary == "": summary = "Add credit line with title from Geograph" else: summary += "; add credit line with title from Geograph" bot.log("edit summary: %s" % (summary, )) # Before we save, make sure pywikibot's view of the latest # revision hasn't changed. If it has, that invalidates # our parse tree, and we need to start again. if page.latest_revision_id != revid: bot.log("page has changed (%d != %d): restarting edit" % (page.latest_revision_id, revid)) self.process_page(page) return page.text = newtext page.save(summary, minor=minor)
def process_page(self, page): camera_action = None object_action = None sdc_camera_action = None sdc_object_action = None creditline_added = False sdc_edits = {} revid = page.latest_revision_id tree = mwparserfromhell.parse(page.text) try: gridimage_id = get_gridimage_id(tree) except ValueError as e: raise BadTemplate(str(e)) except IndexError as e: raise BadTemplate(str(e)) mapit = MapItSettings() c = geodb.cursor() c.execute(""" SELECT * FROM gridimage_base NATURAL JOIN gridimage_geo NATURAL JOIN gridimage_extra WHERE gridimage_id = ? """, (gridimage_id,)) row = c.fetchone() if row == None: raise NotInGeographDatabase("Geograph ID %d not in database" % (gridimage_id,)) try: old_location = get_location(tree) except IndexError: old_location = None try: old_object_location = get_object_location(tree) except IndexError: old_object_location = None minor = False # May need fixing bot.log("Old cam: %s" % (old_location,)) bot.log("Old obj: %s" % (old_object_location,)) if old_location == None and old_object_location == None: minor = False mapit.allowed = True # No geocoding at all: add from Geograph new_location = location_from_row(row, mapit=mapit) new_object_location = object_location_from_row(row, mapit=mapit) if new_location and new_location.get('prec').value != '1000': set_location(tree, new_location) camera_action = 'add' set_object_location(tree, new_object_location) object_action = 'add' else: oldcamparam = location_params(old_location) oldobjparam = location_params(old_object_location) if ((old_location == None or re.match(r'^geograph(-|$)', oldcamparam.get('source',''))) and (old_object_location == None or re.match(r'^geograph(-|$)', oldobjparam.get('source','')))): bot.log("Old geocoding is from Geograph") # Existing geocoding all from Geograph, so updating # from Geograph OK if needed. new_location = location_from_row(row, mapit=mapit) new_object_location = object_location_from_row(row, mapit=mapit) # Should we update locations? should_set_cam = self.should_set_location( old_location, new_location, "camera") should_set_obj = self.should_set_location( old_object_location, new_object_location, "object") if ((should_set_cam and old_location != None) or (should_set_obj and old_object_location != None)): # Check if SDC has location templates. statements = self.get_sdc_statements(page) for s in statements.get('P1259', []): if (should_set_cam and old_location != None and statement_matches_template(s, old_location)): s_new = camera_statement_from_row(row) if s_new == None: s_new = dict(id=s['id'], remove="") bot.log("Removing %s statement %s" % (s['mainsnak']['property'], s['id'])) sdc_camera_action = 'remove' else: s_new['id'] = s['id'] bot.log("Updating %s statement %s" % (s['mainsnak']['property'], s['id'])) sdc_camera_action = 'update' sdc_edits.setdefault('claims', []) sdc_edits['claims'].append(s_new) for s in statements.get('P625', []): if (should_set_obj and old_object_location != None and statement_matches_template(s, old_object_location)): s_new = object_statement_from_row(row) if s_new == None: s_new = dict(id=s['id'], remove="") bot.log("Removing %s statement %s" % (s['mainsnak']['property'], s['id'])) sdc_object_action = 'remove' else: s_new['id'] = s['id'] bot.log("Updating %s statement %s" % (s['mainsnak']['property'], s['id'])) sdc_object_action = 'update' sdc_edits.setdefault('claims', []) sdc_edits['claims'].append(s_new) # Do it if necessary: mapit.allowed = True if should_set_cam: set_location(tree, location_from_row(row, mapit=mapit)) if old_location == None: if new_location != None: camera_action = 'add' else: if new_location == None: camera_action = 'remove' else: camera_action = 'update' if should_set_obj: set_object_location(tree, object_location_from_row(row, mapit=mapit)) if old_object_location == None: if new_object_location != None: object_action = 'add' else: if new_object_location == None: object_action = 'remove' else: object_action = 'update' creditline = creditline_from_row(row) if (can_add_creditline(tree, creditline) and self.unmodified_on_geograph_since_upload(page, row)): add_creditline(tree, creditline) creditline_added = True minor = False else: bot.log("Cannot add credit line") newtext = str(tree) if newtext != page.text: format_params = dict(row=format_row(row)) if camera_action == 'update': format_params['camera_move'] = ( self.describe_move(old_location, new_location)) if object_action == 'update': format_params['object_move'] = ( self.describe_move(old_object_location, new_object_location)) summary = (self.summary_formats[(camera_action, object_action)] .format(**format_params)) if creditline_added: if summary == "": summary = "Add credit line with title from Geograph" else: summary += "; add credit line with title from Geograph" if mapit.used: # Requested credit where MapIt is used: # 'Please attribute us with the text “Powered by Mapit” # and a link back to the MapIt front page.' summary += ( " [powered by MapIt: http://global.mapit.mysociety.org]") bot.log("edit summary: %s" % (summary,)) # Before we save, make sure pywikibot's view of the latest # revision hasn't changed. If it has, that invalidates # our parse tree, and we need to start again. if page.latest_revision_id != revid: bot.log("page has changed (%d != %d): restarting edit" % (page.latest_revision_id, revid)) self.process_page(page) return page.text = newtext page.save(summary, minor=minor) if sdc_edits: sdc_summary = (self.summary_formats[(sdc_camera_action, sdc_object_action)] .format(**format_params)) bot.log("SDC edit summary: %s" % (sdc_summary,)) self.site._simple_request( action='wbeditentity', format='json', id='M%d' % (page.pageid,), data=json.dumps(sdc_edits), token=self.site.tokens['csrf'], summary=sdc_summary, bot=True, baserevid=revid).submit()