Skip to content

Commit

Permalink
Map-Chat / Crowd Sourced Data (#4596)
Browse files Browse the repository at this point in the history
* Update main.js

* Update map.js

* Create social_handler.py

* Update __init__.py

* Update pokecli.py

* Update requirements.txt

* Update __init__.py

* Update config.json.example

* Update config.json.cluster.example

* Update config.json.map.example

* Update config.json.optimizer.example

* Update config.json.path.example

* Update config.json.pokemon.example

* To make CI happy.
  • Loading branch information
BreezeRo authored Aug 23, 2016
1 parent 2244464 commit 4836de0
Show file tree
Hide file tree
Showing 13 changed files with 200 additions and 50 deletions.
1 change: 1 addition & 0 deletions configs/config.json.cluster.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"encrypt_location": "",
"websocket_server": false,
"heartbeat_threshold": 10,
"enable_social": true,
"tasks": [
{
"type": "HandleSoftBan"
Expand Down
1 change: 1 addition & 0 deletions configs/config.json.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"encrypt_location": "",
"websocket_server": false,
"heartbeat_threshold": 10,
"enable_social": true,
"tasks": [
{
"type": "HandleSoftBan"
Expand Down
1 change: 1 addition & 0 deletions configs/config.json.map.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"encrypt_location": "",
"websocket_server": false,
"heartbeat_threshold": 10,
"enable_social": true,
"tasks": [
{
"type": "HandleSoftBan"
Expand Down
1 change: 1 addition & 0 deletions configs/config.json.optimizer.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"encrypt_location": "",
"websocket_server": false,
"heartbeat_threshold": 10,
"enable_social": true,
"tasks": [
{
"type": "HandleSoftBan"
Expand Down
1 change: 1 addition & 0 deletions configs/config.json.path.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"encrypt_location": "",
"websocket_server": false,
"heartbeat_threshold": 10,
"enable_social": true,
"tasks": [
{
"type": "HandleSoftBan"
Expand Down
1 change: 1 addition & 0 deletions configs/config.json.pokemon.example
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"encrypt_location": "",
"websocket_server": false,
"heartbeat_threshold": 10,
"enable_social": true,
"tasks": [
{
"type": "HandleSoftBan"
Expand Down
54 changes: 23 additions & 31 deletions map-chat/javascript/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,43 +4,34 @@ var retryCount = 10;

// Support dynamic topic registration by #word
var urlHashTopic = location.hash ? location.hash.substring(1).toLowerCase() : null;
var topic = urlHashTopic ? urlHashTopic : "pgomapcatch";
var topic = urlHashTopic ? urlHashTopic : "pgomapcatch/chat";

function initialiseEventBus(){
window.client = mqtt.connect('ws://test.mosca.io'); // you add a ws:// url here
client.subscribe("pgomapcatch/#");

client.on("message", function(topic, payload) {
//alert([topic, payload].join(": "));
//client.end();

Materialize.toast(payload, 2000);

//@ro: let's grab the message and split that shit. (simple for now, maybe we could just parse the json instead)
var pLoadR = payload.toString();
var pLoadR2 = pLoadR.split(",");
var olat = pLoadR2[0]
var olong = pLoadR2[1]

displayMessageOnMap(payload, olat, olong);
console.log('Topic is '+topic)

Materialize.toast(payload, 4000);
if(topic === 'pgomapcatch/chat'){
console.log('Chatting event')
displayChatMessageOnMap(payload)
} else {

//@ro: let's grab the message and split that shit. (simple for now, maybe we could just parse the json instead)
var pLoadR = payload.toString();
var pLoadR2 = pLoadR.split(",");
var olat = pLoadR2[0]
var olong = pLoadR2[1]
var sessid = pLoadR2[2]

displayMessageOnMap(payload, olat, olong, sessid);
}
});

client.publish("pgomapcatch", "I just connected to the map!");
/*eb = new vertx.EventBus("http://localhost:8080/chat");
eb.onopen = function () {
subscribe(topic);
};
eb.onclose = function(){
if (retryCount) {
retryCount--;
console.log('Connection lost, scheduling reconnect');
setTimeout(initialiseEventBus, 1000);
} else{
Materialize.toast('Connection lost, please refresh :( ', 10000);
}
};*/
client.publish("pgochat/join", "I just connected to the map!");
}

function sendMessage(topic, input) {
Expand All @@ -53,7 +44,8 @@ function sendMessage(topic, input) {
function publish(address, message) {
if (window.client) {
var json = createMessage(message);
window.client.publish(address, json);
window.client.publish(address, JSON.stringify(json.text));
console.log(json);
}
}

Expand All @@ -67,13 +59,13 @@ $( document ).ready(function() {
var input = $("#input");
input.keyup(function (e) {
if (e.keyCode == 13) {
sendMessage(topic, input);
sendMessage('pgomapcatch/chat', input);
}
});
input.focus();

$("#send-button").click(function(){
sendMessage(topic, input);
sendMessage('pgomapcatch/chat', input);
});

$("#notification_lever").change(function() {
Expand Down
118 changes: 105 additions & 13 deletions map-chat/javascript/map.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,31 +124,26 @@ function createMessage(text){
text: text
};
}

function displayMessageOnMap(msg, olat, olong){

// @ro: passing values split from incoming payload into two variables for now (lat and long)
var newPosition = new google.maps.LatLng(olat, olong);
function displayChatMessageOnMap(raw){
var msg = JSON.parse(raw)
console.log(msg)
var newPosition = new google.maps.LatLng(msg.lat,msg.lng);
var msgSessionId = msg.sessionId;

// @ro: just checking the output
console.log(olat);
console.log(olong);


// xss prevention hack
msg.text = html_sanitize(msg.text);

msg.text = String(msg.text).replace(/[&<>"#'\/]/g, function (s) {
return entityMap[s];
});

// msg.text = msg.text ? embedTweet(msg.text) : "";
// msg.text = msg.text ? embedTweet(msg.text) : "";
msg.text = msg.text.replace(/&#35;(\S*)/g,'<a href="http://idoco.github.io/map-chat/#$1" target="_blank">#$1</a>');

// linkify
msg.text = msg.text.replace(/(\b(https?|ftp|file):&#x2F;&#x2F;[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,
"<a target='_blank' href='$1'>$1</a>");

if(markersMap[msgSessionId]){ // update existing marker
var existingMarker = markersMap[msgSessionId].marker;
var existingInfoWindow = markersMap[msgSessionId].infoWindow;
Expand Down Expand Up @@ -196,7 +191,104 @@ function displayMessageOnMap(msg, olat, olong){

if (msg.text) {
infoWindow.open(map, marker);

}

var timeoutId = setTimeout(function() { infoWindow.close() }, 10000);
markersMap[msgSessionId] = {
marker: marker,
infoWindow: infoWindow,
timeoutId: timeoutId,
disabled: false
}
}

if (advanced){
runAdvancedOptions(msg);
}
}

function displayMessageOnMap(msg, olat, olong, sessid){

// @ro: passing values split from incoming payload into two variables for now (lat and long)
var newPosition = new google.maps.LatLng(olat, olong);
var msgSessionId = sessid;

// @ro: just checking the output
console.log(olat);
console.log(olong);

// xss prevention hack
msg.text = html_sanitize(msg.text);

msg.text = String(msg.text).replace(/[&<>"#'\/]/g, function (s) {
return entityMap[s];
});

// msg.text = msg.text ? embedTweet(msg.text) : "";
msg.text = msg.text.replace(/&#35;(\S*)/g,'<a href="http://idoco.github.io/map-chat/#$1" target="_blank">#$1</a>');

// linkify
msg.text = msg.text.replace(/(\b(https?|ftp|file):&#x2F;&#x2F;[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,
"<a target='_blank' href='$1'>$1</a>");

if(markersMap[msgSessionId]){ // update existing marker
var infoWindow = new google.maps.InfoWindow({
content: msg.text,
maxWidth: 400,
disableAutoPan: true,
zIndex: infoWindowZIndex
});
infoWindowZIndex++;

var marker = new google.maps.Marker({
position: newPosition,
map: map,
draggable: false,
icon: markerImage,
title: "Click to mute/un-mute User "+msgSessionId
});

marker.addListener('click',function() {
if (markersMap[msgSessionId].disabled) {
markersMap[msgSessionId].disabled = false;
marker.setIcon(markerImage);
} else{
markersMap[msgSessionId].disabled = true;
marker.setIcon(disabledMarkerImage);
infoWindow.close();
}
});
} else { // new marker
var infoWindow = new google.maps.InfoWindow({
content: msg.text,
maxWidth: 400,
disableAutoPan: true,
zIndex: infoWindowZIndex
});
infoWindowZIndex++;

var marker = new google.maps.Marker({
position: newPosition,
map: map,
draggable: false,
icon: markerImage,
title: "Click to mute/un-mute User "+msgSessionId
});

marker.addListener('click',function() {
if (markersMap[msgSessionId].disabled) {
markersMap[msgSessionId].disabled = false;
marker.setIcon(markerImage);
} else{
markersMap[msgSessionId].disabled = true;
marker.setIcon(disabledMarkerImage);
infoWindow.close();
}
});

if (msg.text) {
infoWindow.open(map, marker);

}

var timeoutId = setTimeout(function() { infoWindow.close() }, 10000);
Expand Down
12 changes: 10 additions & 2 deletions pokecli.py
Original file line number Diff line number Diff line change
Expand Up @@ -570,8 +570,16 @@ def _json_loader(filename):
type=float,
default=8.0
)



add_config(
parser,
load,
long_flag="--enable_social",
help="Enable social event exchange between bot",
type=bool,
default=True
)

# Start to parse other attrs
config = parser.parse_args()
if not config.username and 'username' not in load:
Expand Down
9 changes: 5 additions & 4 deletions pokemongo_bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from human_behaviour import sleep
from item_list import Item
from metrics import Metrics
from pokemongo_bot.event_handlers import LoggingHandler, SocketIoHandler, ColoredLoggingHandler
from pokemongo_bot.event_handlers import LoggingHandler, SocketIoHandler, ColoredLoggingHandler, SocialHandler
from pokemongo_bot.socketio_server.runner import SocketIoRunner
from pokemongo_bot.websocket_remote_control import WebsocketRemoteControl
from pokemongo_bot.base_dir import _base_dir
Expand Down Expand Up @@ -117,7 +117,8 @@ def _setup_event_system(self):
handlers.append(ColoredLoggingHandler())
else:
handlers.append(LoggingHandler())

if self.config.enable_social:
handlers.append(SocialHandler(self))
if self.config.websocket_server_url:
if self.config.websocket_start_embedded_server:
self.sio_runner = SocketIoRunner(self.config.websocket_server_url)
Expand Down Expand Up @@ -1059,14 +1060,14 @@ def get_pos_by_name(self, location_name):
possible_coordinates = re.findall(
"[-]?\d{1,3}[.]\d{3,7}", location_name
)
if len(possible_coordinates) >= 2:
if len(possible_coordinates) == 2:
# 2 matches, this must be a coordinate. We'll bypass the Google
# geocode so we keep the exact location.
self.logger.info(
'[x] Coordinates found in passed in location, '
'not geocoding.'
)
return float(possible_coordinates[0]), float(possible_coordinates[1]), (float(possible_coordinates[2]) if len(possible_coordinates) == 3 else self.alt)
return float(possible_coordinates[0]), float(possible_coordinates[1]), self.alt

geolocator = GoogleV3(api_key=self.config.gmapkey)
loc = geolocator.geocode(location_name, timeout=10)
Expand Down
1 change: 1 addition & 0 deletions pokemongo_bot/event_handlers/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from logging_handler import LoggingHandler
from socketio_handler import SocketIoHandler
from colored_logging_handler import ColoredLoggingHandler
from social_handler import SocialHandler
49 changes: 49 additions & 0 deletions pokemongo_bot/event_handlers/social_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# -*- coding: utf-8 -*-
from pokemongo_bot.event_manager import EventHandler
import thread
import paho.mqtt.client as mqtt
class MyMQTTClass:
def __init__(self, clientid=None):
self._mqttc = mqtt.Client(clientid)
self._mqttc.on_message = self.mqtt_on_message
#self._mqttc.on_connect = self.mqtt_on_connect
#self._mqttc.on_publish = self.mqtt_on_publish
#self._mqttc.on_subscribe = self.mqtt_on_subscribe
#def mqtt_on_connect(self, mqttc, obj, flags, rc):
#print "rc: "+str(rc)
def mqtt_on_message(self, mqttc, obj, msg):
print msg.topic+" "+str(msg.qos)+" "+str(msg.payload)
#def mqtt_on_publish(self, mqttc, obj, mid):
#print "mid: "+str(mid)
#def mqtt_on_subscribe(self, mqttc, obj, mid, granted_qos):
# print "Subscribed: "+str(mid)+" "+str(granted_qos)
#def mqtt_on_log(self, mqttc, obj, level, string):
# print string
def publish(self, channel, message):
self._mqttc.publish(channel, message)
def connect_to_mqtt(self):
self._mqttc.connect("test.mosca.io", 1883, 60)
self._mqttc.subscribe("pgomapcatch/#", 0)
def run(self):
self._mqttc.loop_forever()
class SocialHandler(EventHandler):
def __init__(self, bot):
self.bot = bot
self.mqttc = MyMQTTClass()
self.mqttc.connect_to_mqtt()
thread.start_new_thread(self.mqttc.run)
def handle_event(self, event, sender, level, formatted_msg, data):
#sender_name = type(sender).__name__
#if formatted_msg:
# message = "[{}] {}".format(event, formatted_msg)
#else:
#message = '{}: {}'.format(event, str(data))
if event == 'catchable_pokemon':
#self.mqttc.publish("pgomapcatch/all", str(data))
#print data
if data['pokemon_id']:
#self.mqttc.publish("pgomapcatch/all/catchable/"+str(data['pokemon_id']), str(data))
self.mqttc.publish("pgomapcatch/all/catchable/"+str(data['pokemon_id']), str(data['latitude'])+","+str(data['longitude'])+","+str(data['encounter_id']))

#print 'have catchable_pokemon'
#print message
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,4 @@ raven==5.23.0
demjson==2.2.4
greenlet==0.4.9
yoyo-migrations==5.0.3
paho-mqtt==1.2

0 comments on commit 4836de0

Please sign in to comment.