Skip to content

Commit

Permalink
Merge branch 'master' into m-thread
Browse files Browse the repository at this point in the history
  • Loading branch information
xPMo authored Jul 30, 2022
2 parents 4cafa21 + b34f3eb commit 8b57c17
Show file tree
Hide file tree
Showing 5 changed files with 118 additions and 28 deletions.
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,8 @@ Can search OpenStreetMaps for locations and send Matrix location events from the
Commands:

* !loc [location] - search for location
* !loc enable - enable location to link translation in this room (must be done as room admin)
* !loc disable - disable location to link translation in this room (must be done as room admin)

Example:

Expand Down Expand Up @@ -590,10 +592,10 @@ You can create any number of them.
For example set all machine labels to be #B60205 and space labels to be #0E8A16. These
can be easily picked from color chooser.
* Edit the repository description and add a json block describing the
label domains and their colors. For example:
label domains and their colors (array format supports multiple colors per domain). For example:

```
Hackerspace machines, todo and stuff. domains={ "machines": "#B60205", "spaces" : "#0E8A16"}
Hackerspace machines, todo and stuff. domains={"koneet":["#BFDADC","#0CBBF0","#0CBBF0","#E15D19","#ED49CF"],"tilat":["#0E8A16","#1E8A16"]}
```

Make sure you type the description on one line - this is a silly Github limitation.
Expand Down Expand Up @@ -703,7 +705,7 @@ If your user is not pi, modify hemppa.service first.

``` bash
sudo ln -s `pwd` /opt/hemppa
sudo ln -s hemppa.service /lib/systemd/system
sudo ln -s `pwd`/hemppa.service /lib/systemd/system
sudo systemctl daemon-reload
sudo systemctl enable hemppa.service
sudo systemctl start hemppa.service
Expand Down
5 changes: 3 additions & 2 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ async def send_html(self, room, event, html, plaintext, msgtype="m.notice", bot_
msg["org.vranki.hemppa.ignore"] = "true"
await self.room_send(room.room_id, event, 'm.room.message', msg)

async def send_location(self, room, event, body, latitude, longitude, bot_ignore=False):
async def send_location(self, room, event, body, latitude, longitude, bot_ignore=False, asset='m.pin'):
"""
:param room: A MatrixRoom the html should be send to
Expand All @@ -239,12 +239,14 @@ async def send_location(self, room, event, body, latitude, longitude, bot_ignore
:param latitude: Latitude in WGS84 coordinates (float)
:param longitude: Longitude in WGS84 coordinates (float)
:param bot_ignore: Flag to mark the message to be ignored by the bot
:param asset: Asset string as defined in MSC3488 (such as m.self or m.pin)
:return:
"""
locationmsg = {
"body": str(body),
"geo_uri": 'geo:' + str(latitude) + ',' + str(longitude),
"msgtype": "m.location",
"org.matrix.msc3488.asset": { "type": asset }
}
await self.room_send(room.room_id, event, 'm.room.message', locationmsg)

Expand Down Expand Up @@ -568,7 +570,6 @@ def __handle_error_response(self, response):
sys.exit(2)

def init(self):

self.matrix_user = os.getenv('MATRIX_USER')
matrix_server = os.getenv('MATRIX_SERVER')
bot_owners = os.getenv('BOT_OWNERS')
Expand Down
10 changes: 6 additions & 4 deletions modules/ghproj.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

# Helper class with reusable code for github project stuff
class GithubProject:
# New format to support array of colors: domains={"koneet":["#BFDADC","#0CBBF0","#0CBBF0","#E15D19","#ED49CF"],"tilat":["#0E8A16","#1E8A16"]}
def get_domains(description):
p = re.compile('domains=\{.*\}')
matches = json.loads(p.findall(description)[0][8:])
Expand All @@ -17,16 +18,17 @@ def get_domain(reponame, domain):
domains = GithubProject.get_domains(repo.description)
if(not len(domains)):
return None, None
domain_color = domains.get(domain, None)
if not domain_color:
domain_colors = domains.get(domain, None)
if not domain_colors:
return None, None

open_issues = repo.get_issues(state='open')
domain_labels = []
labels = repo.get_labels()
for label in labels:
if label.color == domain_color[1:]:
domain_labels.append(label)
for domain_color in domain_colors:
if label.color == domain_color[1:]:
domain_labels.append(label)

domain_issues = dict()
domain_ok = []
Expand Down
123 changes: 104 additions & 19 deletions modules/loc.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@


class MatrixModule(BotModule):
bot = None
def __init__(self, name):
super().__init__(name)
self.bot = None
self.enabled_rooms = []

def matrix_start(self, bot):
super().matrix_start(bot)
Expand All @@ -16,30 +19,87 @@ def matrix_stop(self, bot):
super().matrix_stop(bot)
bot.remove_callback(self.unknown_cb)

'''
Location events are like: https://spec.matrix.org/v1.2/client-server-api/#mlocation
{
"content": {
"body": "geo:61.49342512194717,23.765914658307736",
"geo_uri": "geo:61.49342512194717,23.765914658307736",
"msgtype": "m.location",
"org.matrix.msc1767.text": "geo:61.49342512194717,23.765914658307736",
"org.matrix.msc3488.asset": {
"type": "m.pin"
},
"org.matrix.msc3488.location": {
"description": "geo:61.49342512194717,23.765914658307736",
"uri": "geo:61.49342512194717,23.765914658307736"
},
"org.matrix.msc3488.ts": 1653837929839
},
"room_id": "!xsBGdLYGrfYhGfLtHG:hacklab.fi",
"type": "m.room.message"
}
BUT sometimes there's ; separating altitude??
{
"content": {
"body": "geo:61.4704211,23.4864855;36.900001525878906",
"geo_uri": "geo:61.4704211,23.4864855;36.900001525878906",
"msgtype": "m.location",
"org.matrix.msc1767.text": "geo:61.4704211,23.4864855;36.900001525878906",
"org.matrix.msc3488.asset": {
"type": "m.self"
},
"org.matrix.msc3488.location": {
"description": "geo:61.4704211,23.4864855;36.900001525878906",
"uri": "geo:61.4704211,23.4864855;36.900001525878906"
},
"org.matrix.msc3488.ts": 1653931683087
},
"origin_server_ts": 1653931683998,
"sender": "@cos:hacklab.fi",
"type": "m.room.message",
"unsigned": {
"age": 70
},
"event_id": "$6xXutKF9EppPMMdc4aQLZjHyd8My0rIZuNZEcuSIPws",
"room_id": "!CLofqdurVWZCMpFnqM:hacklab.fi"
}
'''

async def unknown_cb(self, room, event):
if event.msgtype != 'm.location':
return
if room.room_id not in self.enabled_rooms:
return
location_text = event.content['body']

# Fallback if body is empty
if len(location_text) == 0:
if (len(location_text) == 0) or ('geo:' in location_text):
location_text = 'location'

sender_response = await self.bot.client.get_displayname(event.sender)
sender = sender_response.displayname

geo_uri = event.content['geo_uri']
latlon = geo_uri.split(':')[1].split(',')
try:
geo_uri = geo_uri[4:] # Strip geo:

# Sanity checks to avoid url manipulation
float(latlon[0])
float(latlon[1])
if ';' in geo_uri: # Strip altitude, if present
geo_uri = geo_uri.split(';')[0]
latlon = geo_uri.split(',')

# Sanity checks to avoid url manipulation
float(latlon[0])
float(latlon[1])
except Exception:
self.bot.send_text(room, "Error: Invalid location " + geo_uri)
return

osm_link = 'https://www.openstreetmap.org/?mlat=' + \
latlon[0] + "&mlon=" + latlon[1]
osm_link = f"https://www.openstreetmap.org/?mlat={latlon[0]}&mlon={latlon[1]}"

plain = sender + ' 🚩 ' + osm_link
html = f'{sender} 🚩 <a href="{osm_link}">{location_text}</a>'
plain = f'{sender} sent {location_text} {osm_link} 🚩'
html = f'{sender} sent <a href="{osm_link}">{location_text}</a> 🚩'

await self.bot.send_html(room, event, html, plain)

Expand All @@ -48,16 +108,41 @@ async def matrix_message(self, bot, room, event):
args.pop(0)
if len(args) == 0:
await bot.send_text(room, event, 'Usage: !loc <location name>')
return
elif len(args) == 1:
if args[0] == 'enable':
bot.must_be_admin(room, event)
self.enabled_rooms.append(room.room_id)
self.enabled_rooms = list(dict.fromkeys(self.enabled_rooms)) # Deduplicate
await bot.send_text(room, event, "Ok, sending locations events here as text versions")
bot.save_settings()
return
if args[0] == 'disable':
bot.must_be_admin(room, event)
self.enabled_rooms.remove(room.room_id)
await bot.send_text(room, event, "Ok, disabled here")
bot.save_settings()
return

query = event.body[4:]
geolocator = Nominatim(user_agent=bot.appid)
self.logger.info('loc: looking up %s ..', query)
location = geolocator.geocode(query)
self.logger.info('loc rx %s', location)
if location:
await bot.send_location(room, event, location.address, location.latitude, location.longitude, "m.pin")
else:
query = event.body[4:]
geolocator = Nominatim(user_agent=bot.appid)
self.logger.info('loc: looking up %s ..', query)
location = geolocator.geocode(query)
self.logger.info('loc rx %s', location)
if location:
await bot.send_location(room, event, location.address, location.latitude, location.longitude)
else:
await bot.send_text(room, event, "Can't find " + query + " on map!")
await bot.send_text(room, event, "Can't find " + query + " on map!")

def help(self):
return 'Search for locations and display Matrix location events as OSM links'

def get_settings(self):
data = super().get_settings()
data["enabled_rooms"] = self.enabled_rooms
return data

def set_settings(self, data):
super().set_settings(data)
if data.get("enabled_rooms"):
self.enabled_rooms = data["enabled_rooms"]
Empty file modified run.sh
100644 → 100755
Empty file.

0 comments on commit 8b57c17

Please sign in to comment.