Skip to content

Commit

Permalink
feat: switch to jamix api (#8)
Browse files Browse the repository at this point in the history
* initial working json parsing

* fix allergen printing

* fix date url param

* tidy up print
  • Loading branch information
jkerola authored Aug 28, 2023
1 parent 45f215a commit e5cdc50
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 54 deletions.
40 changes: 33 additions & 7 deletions jmenu/restaurants.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,40 @@
from collections import namedtuple

Restaurant = namedtuple("Restaurant", ["name", "url"])
Restaurant = namedtuple(
"Restaurant", ["name", "client_id", "kitchen_id", "menu_type", "relevant_menus"]
)
Marking = namedtuple("Marking", ["letters", "explanation"])

API_URL = "https://fi.jamix.cloud/apps/menuservice/rest/haku/menu"

SKIPPED_ITEMS = [
"proteiinilisäke",
"Täysjyväriisi",
"Lämmin kasvislisäke",
"Höyryperunat",
"Tumma pasta",
"Meillä tehty perunamuusi",
]

RESTAURANTS = [
Restaurant("Foobar", "https://fi.jamix.cloud/apps/menu/?anro=93077&k=49&mt=84"),
Restaurant("Foodoo", "https://fi.jamix.cloud/apps/menu/?anro=93077&k=48&mt=89"),
Restaurant("Kastari", "https://fi.jamix.cloud/apps/menu/?anro=95663&k=5&mt=2"),
Restaurant("Kylmä", "https://fi.jamix.cloud/apps/menu/?anro=93077&k=48&mt=92"),
Restaurant("Mara", "https://fi.jamix.cloud/apps/menu/?anro=93077&k=49&mt=111"),
Restaurant("Napa", "https://fi.jamix.cloud/apps/menu/?anro=93077&k=48&mt=79"),
Restaurant(
"Foobar",
93077,
49,
84,
["Foobar Salad and soup", "Foobar Rohee"],
),
Restaurant(
"Foodoo",
93077,
48,
89,
["Foodoo Salad and soup", "Foodoo Reilu"],
),
Restaurant("Kastari", 95663, 5, 2, ["Ruokalista"]),
Restaurant("Kylmä", 93077, 48, 92, []),
Restaurant("Mara", 93077, 49, 111, ["Salad and soup", "Ravintola Mara"]),
Restaurant("Napa", 93077, 48, 79, []),
]

MARKINGS = [
Expand Down
90 changes: 43 additions & 47 deletions jmenu/utils.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,9 @@
from version import VERSION
from restaurants import RESTAURANTS, MARKINGS
from restaurants import RESTAURANTS, MARKINGS, API_URL, SKIPPED_ITEMS, Restaurant
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
from selenium.webdriver.chrome.options import Options
import requests
import argparse
from time import time
from webdriver_manager.chrome import ChromeDriverManager


class ArgsNamespace:
Expand Down Expand Up @@ -61,57 +54,58 @@ def get_args():
return parser.parse_args(namespace=ArgsNamespace())


def get_selenium_opts() -> Options:
opts = Options()
opts.add_argument("--headless")
return opts


def get_soup(url: str) -> BeautifulSoup:
try:
driver = webdriver.Chrome(
service=ChromeService(ChromeDriverManager().install()),
options=get_selenium_opts(),
)
driver.get(url)
cond = expected_conditions.presence_of_element_located(
(
By.CLASS_NAME,
"v-customlayout-header",
)
)
WebDriverWait(driver, 5).until(cond)
soup = BeautifulSoup(driver.page_source, "html.parser")
return soup
except Exception:
pass


def parse_soup(soup: BeautifulSoup) -> list[str]:
results = soup.find_all("div", attrs={"class": "menu-sub-view"})
if len(results) == 0:
def get_restaurant_menu_items(rest: Restaurant) -> list[dict]:
today = datetime.now().strftime("%Y%m%d")
response = requests.get(
f"{API_URL}/{rest.client_id}/{rest.kitchen_id}?lang=fi&date={today}"
)
data = response.json()
menus = get_menus(data, rest)
if len(menus) == 0:
return []
results = soup.find_all("span", attrs={"class": "menu-item"})
menu = [result.text for result in results]
return menu
items = get_menu_items(menus, rest)
return items


def get_menu_items(menus: dict, rest: Restaurant) -> list[dict]:
items = []
for menu in menus:
day = menu["days"][0]
mealopts = day["mealoptions"]
sorted(mealopts, key=lambda x: x["orderNumber"])
for opt in mealopts:
for item in opt["menuItems"]:
if item["name"] not in SKIPPED_ITEMS:
items.append(item)
return items


def get_menus(data: dict, rest: Restaurant) -> list[dict]:
menus = []
for kitchen in data:
for m_type in kitchen["menuTypes"]:
if m_type["menuTypeName"] in rest.relevant_menus:
menus.extend(m_type["menus"])
return menus


def print_menu(args: ArgsNamespace):
allergens = []
if args.allergens:
allergens = [" " + x.upper() for x in args.allergens]
allergens = [x.upper() for x in args.allergens]

print_header()
for res in RESTAURANTS:
try:
items = parse_soup(get_soup(res.url))
items = get_restaurant_menu_items(res)
sorted(items, key=lambda x: x["orderNumber"])
if len(items) == 0:
print(res.name, "\t --")
else:
print(res.name)
if not allergens:
for item in items:
print("\t", item)
print("\t", item["name"], item["diets"])
else:
print_highlight(items, allergens)

Expand All @@ -126,10 +120,12 @@ def print_explanations():

def print_highlight(items: list[str], allergens: list[str]):
for item in items:
if any(marker in item for marker in allergens):
print("\033[92m", "\t", item, "\033[0m")
diets = item["diets"].split(",")
diets = [marker.strip() for marker in diets]
if all(marker in diets for marker in allergens):
print("\033[92m", "\t", item["name"], item["diets"], "\033[0m")
else:
print("\t", item)
print("\t", item["name"], item["diets"])


def print_header():
Expand Down

0 comments on commit e5cdc50

Please sign in to comment.