Bläddra i källkod

Converted all of code to python except pikante

Toni Fadjukoff 8 år sedan
förälder
incheckning
0a74cd1676
6 ändrade filer med 123 tillägg och 27 borttagningar
  1. 61 2
      amica.py
  2. 12 12
      food.py
  3. 4 7
      juvenes.py
  4. 1 3
      pikante.py
  5. 1 1
      ruoka.js
  6. 44 2
      sodexo.py

+ 61 - 2
amica.py Visa fil

@@ -1,8 +1,67 @@
1
+import datetime
2
+import os
3
+import urllib.request
4
+import urllib.error
5
+import json
6
+
1 7
 restaurant_info = [
2 8
   [ "(TaY) Amica Minerva", "http://www.amica.fi/minerva", "", "middle", "http://www.amica.fi/api/restaurant/menu/week?language=fi&restaurantPageId=7381" ],
3 9
   [ "(TaY) Tampereen normaalikoulun ravintola", "http://www.amica.fi/tampereennormaalikoulu", "", "middle", "http://www.amica.fi/api/restaurant/menu/week?language=fi&restaurantPageId=6655" ],
4 10
   [ "(TTY) Ravintola Reaktori", "http://www.amica.fi/reaktori", "", "middle", "http://www.amica.fi/api/restaurant/menu/week?language=fi&restaurantPageId=69171" ]
5 11
 ]
6 12
 
7
-def get_restaurants(use_old):
8
-    return []
13
+def get_restaurants(use_old, week):
14
+    today = datetime.date.today()
15
+    week_day = today.isocalendar()[2]
16
+    this_monday = today - datetime.timedelta(days=week_day-1)
17
+    week_date = this_monday.strftime("%Y-%m-%d")
18
+    restaurants = []
19
+    for count, info in enumerate(restaurant_info):
20
+        title = info[0]
21
+        url = info[4]
22
+        temp_fname = "amica_{count}.temp.js".format(count = count)
23
+        url = "{url}&weekDate={week_date}".format(url=url, week_date=week_date)
24
+        if not use_old or not os.path.isfile(temp_fname):
25
+            try:
26
+                urllib.request.urlretrieve(url, temp_fname)
27
+            except urllib.error.HTTPError as e:
28
+                print("Failed to download {url}".format(url=url))
29
+        try:
30
+            with open(temp_fname, "r", encoding="utf-8") as fin:
31
+                data = json.load(fin)
32
+        except OSError as e:
33
+            continue
34
+
35
+        week_foods = {}
36
+        lunch_menus = data["LunchMenus"]
37
+        for week_day, lunch_menu in enumerate(lunch_menus):
38
+            current_day_foods = []
39
+            set_menus = lunch_menu["SetMenus"]
40
+            html = lunch_menu["Html"]
41
+            if len(html):
42
+                menus = html.split("<p>")
43
+                for set_menu in menus:
44
+                    meals = set_menu.split("<br />")
45
+                    food = []
46
+                    for meal in meals:
47
+                        parts = meal.split("(")
48
+                        current_food = parts[0]
49
+                        diets = [s.strip() for s in parts.split(")")[0].split(",")]
50
+                        if diets:
51
+                            current_food += " ({allergies})".format(allergies=", ".join(diets))
52
+                        food.append(current_food)
53
+                    current_day_foods.append("\n".join(food))
54
+            else:
55
+                for set_menu in set_menus:
56
+                    meals = set_menu["Meals"]
57
+                    food = []
58
+                    for meal in meals:
59
+                        current_food = meal["Name"]
60
+                        if "Diets" in meal:
61
+                            current_food += " ({allergies})".format(allergies=", ".join(meal["Diets"]))
62
+                        food.append(current_food)
63
+                    current_day_foods.append("\n".join(food))
64
+            week_foods[week_day] = current_day_foods
65
+
66
+        restaurants.append([title, "", week, week_foods, info])
67
+    return restaurants

+ 12 - 12
food.py Visa fil

@@ -40,10 +40,10 @@ unordered = []
40 40
 l = time.localtime()
41 41
 this_week = datetime.datetime.now().isocalendar()[1]
42 42
 
43
-unordered += amica.get_restaurants(use_old)
44
-unordered += juvenes.get_restaurants(use_old)
45
-unordered += sodexo.get_restaurants(use_old)
46
-unordered += pikante.get_restaurants(use_old)
43
+unordered += amica.get_restaurants(use_old, this_week)
44
+unordered += juvenes.get_restaurants(use_old, this_week)
45
+unordered += sodexo.get_restaurants(use_old, this_week)
46
+unordered += pikante.get_restaurants(use_old, this_week)
47 47
 
48 48
 print(unordered)
49 49
 
@@ -103,7 +103,6 @@ file_footer = """
103 103
   </body>
104 104
 </html>
105 105
 """.format(stamp=time.strftime("%d.%m.%Y %H:%M:%S"))
106
-print(file_footer)
107 106
 
108 107
 def find_last_day_with_foods(restaurants):
109 108
     last_day = 0
@@ -152,7 +151,7 @@ def write_day(day, header, outfname, last_day, restaurants, prefix, resources_pr
152 151
     with open(outfname, "w", encoding="utf-8") as fout:
153 152
         import types
154 153
         def write(self, writable):
155
-            print("Writing {}: {}".format(type(writable), writable))
154
+            #print("Writing {}: {}".format(type(writable), writable))
156 155
             self.write_orig(writable)
157 156
         fout.write_orig = fout.write
158 157
         fout.write = types.MethodType(write, fout)
@@ -221,7 +220,7 @@ def write_day(day, header, outfname, last_day, restaurants, prefix, resources_pr
221 220
                         part_count += 1
222 221
 
223 222
                         # add missing () around allergies
224
-                        part = re.sub(" (([MLGK]|VL|Ve|Veg|Hot)(,([MLGK]|VL|Ve|Veg|Hot|))+)$", " (\\1)", part)
223
+                        part = re.sub(" (([MLGKA]|VL|Ve|VE|Veg|Hot)(, *([MLGKA]|VL|Ve|VE|Veg|Hot|))+)$", " (\\1)", part)
225 224
                         match = re.match("^(.*) \\(([^\\)]+)\\)$", part)
226 225
                         if match:
227 226
                             # fix allergy issues
@@ -306,8 +305,8 @@ def write_day(day, header, outfname, last_day, restaurants, prefix, resources_pr
306 305
             fout.write("eatable_foods[\"{a}\"] = [{eatable_food_number}];\n".format(a=a, eatable_food_number=",".join(str(e) for e in eatable_food_numbers[a])))
307 306
             fout.write("maybe_eatable_foods[\"{a}\"] = [{maybe_eatable_food_number}];\n".format(a=a, maybe_eatable_food_number=",".join(str(e) for e in maybe_eatable_food_numbers[a])))
308 307
         allergy_string = ",".join('"{a}"'.format(a=a) for a in allergies)
309
-        fout.write("var allergies = {allergies}];\n".format(allergies = allergy_string))
310
-        fout.write("var food_count = $foodnum;\n")
308
+        fout.write("var allergies = [{allergies}];\n".format(allergies = allergy_string))
309
+        fout.write("var food_count = {foodnum};\n".format(foodnum = foodnum))
311 310
         fout.write("window.onload = function() { set_allergies(); show_warning(); };\n")
312 311
         fout.write("</script>\n")
313 312
         fout.write("</div></div>{file_footer}".format(file_footer=file_footer.format(resources_prefix=resources_prefix)))
@@ -333,9 +332,10 @@ def write_all_days(restaurants, prefix, title, resources_prefix):
333 332
 def write_table(restaurants, prefix, title, resources_prefix):
334 333
     last_day = find_last_day_with_foods(restaurants);
335 334
     outfname = "{prefix}table.html".format(prefix=prefix)
336
-    with open(outfname, "w") as fout:
335
+    with open(outfname, "w", encoding="utf-8") as fout:
337 336
         header = "{title} vko {max_week}{max_week_daterange}".format(title=title, max_week=max_week, max_week_daterange=max_week_daterange)
338
-        fout.write("{file_header}<h1>{header}</h1>\n".format(file_header=file_header, header=header))
337
+        fout.write(file_header.format(resources_prefix=resources_prefix))
338
+        fout.write("<h1>{header}</h1>\n".format(header=header))
339 339
         fout.write("<div class=\"title\">\n")
340 340
 
341 341
         write_days_header(fout, -1, last_day)
@@ -345,7 +345,7 @@ def write_table(restaurants, prefix, title, resources_prefix):
345 345
             (title, open_hours, week, week_foods, info) = r
346 346
             (title2, url) = info[0:2]
347 347
             url = re.sub("&", "&nbsp;", url)
348
-            fout.write("<th><a href=\"{url}\">{title}</a></th>")
348
+            fout.write("<th><a href=\"{url}\">{title}</a></th>".format(url=url, title=title))
349 349
         fout.write("</tr>\n")
350 350
         for day in range(last_day):
351 351
             fout.write("<tr><td>{day_name}</td>\n".format(day_name=day_names[day]))

+ 4 - 7
juvenes.py Visa fil

@@ -24,21 +24,19 @@ restaurant_info = [
24 24
 ]
25 25
 
26 26
 
27
-def get_restaurants(use_old):
28
-    count = 0
27
+def get_restaurants(use_old, week):
29 28
     restaurants = []
30
-    for info in restaurant_info:
29
+    for count, info in enumerate(restaurant_info):
31 30
         kitchen = info[4]
32 31
         menutype = info[5]
33 32
         title = info[0]
34 33
         cur_title = title
35 34
         open_hours = ""
36 35
         week_foods = {}
37
-        week = datetime.datetime.now().isocalendar()[1]
38 36
         for weekday in range(1,7):
39 37
             url = "http://www.juvenes.fi/DesktopModules/Talents.LunchMenu/LunchMenuServices.asmx/GetMenuByWeekday?KitchenId={kitchen}&MenuTypeId={menutype}&Week={week}&Weekday={weekday}&lang='fi'&format=json".format(kitchen=kitchen, menutype=menutype, week=week, weekday=weekday)
40 38
             temp_fname = "juvenes_{count}-{weekday}.temp.js".format(count=count, weekday=weekday)
41
-            if not use_old and not os.path.isfile(temp_fname):
39
+            if not use_old or not os.path.isfile(temp_fname):
42 40
                 try:
43 41
                     urllib.request.urlretrieve(url, temp_fname)
44 42
                 except urllib.error.HTTPError as e:
@@ -47,7 +45,7 @@ def get_restaurants(use_old):
47 45
             try:
48 46
                 with open(temp_fname, "r", encoding="utf-8") as fin:
49 47
                     jsonp = fin.read()
50
-                    data = json.loads(jsonp[1:-2])
48
+                data = json.loads(jsonp[1:-2])
51 49
             except OSError as e:
52 50
                 continue
53 51
             if data and data["d"] != "null":
@@ -71,5 +69,4 @@ def get_restaurants(use_old):
71 69
                         cur_day_foods.append("\n".join(cur_food))
72 70
                 week_foods[weekday-1] = cur_day_foods
73 71
         restaurants.append([title, open_hours, week, week_foods, info])
74
-        count += 1
75 72
     return restaurants

+ 1 - 3
pikante.py Visa fil

@@ -1,5 +1,3 @@
1
-# encoding: UTF-8
2
-
3 1
 pikante_url = "http://www.pikante.fi/lounaslistat-pdf";
4 2
 
5 3
 restaurant_info = [
@@ -8,5 +6,5 @@ restaurant_info = [
8 6
   [ "(TAYS) Ellipsi", "$pky_url", "all", "middle" ]
9 7
 ]
10 8
 
11
-def get_restaurants(use_old):
9
+def get_restaurants(use_old, week):
12 10
     return []

+ 1 - 1
ruoka.js Visa fil

@@ -114,7 +114,7 @@ function show_warning() {
114 114
   if (shouldShowWarning()) {
115 115
     var input = document.createElement("input");
116 116
     input.type="submit";
117
-    input.value="Älä näytä tätä enää";
117
+    input.value="Älä näytä tätä enää";
118 118
     input.onclick = function() {
119 119
       notice.parentNode.removeChild(notice); 
120 120
       noMoreWarning();

+ 44 - 2
sodexo.py Visa fil

@@ -1,8 +1,50 @@
1
+import datetime
2
+import os
3
+import urllib.request
4
+import urllib.error
5
+import json
6
+
1 7
 restaurant_info = [
2 8
   [ "(TaY) Sodexo Linna", "http://www.sodexo.fi/linna", "", "right", 92],
3 9
   #[ "(TTY) Sodexo Erkkeri", "http://www.sodexo.fi/erkkeri", "", "left", 100]
4 10
   [ "(TTY) Sodexo Hertsi", "http://www.sodexo.fi/tty-tietotalo", "", "right", 12812]
5 11
 ]
6 12
 
7
-def get_restaurants(use_old):
8
-    return []
13
+def get_restaurants(use_old, week):
14
+    restaurants = []
15
+    for count, info in enumerate(restaurant_info):
16
+        kitchen = info[4]
17
+        title = info[0]
18
+        open_hours = ""
19
+        week_foods = {}
20
+        today = datetime.date.today()
21
+        week_day = today.isocalendar()[2]
22
+        last_sunday = today - datetime.timedelta(days=week_day)
23
+        for weekday in range(1,7):
24
+            date = last_sunday + datetime.timedelta(days=weekday)
25
+            timestr = date.strftime("%Y/%m/%d")
26
+            url = "http://www.sodexo.fi/ruokalistat/output/daily_json/{kitchen}/{timestr}/fi".format(kitchen=kitchen, timestr=timestr)
27
+            temp_fname = "sodexo_{count}-{weekday}.temp.js".format(count=count, weekday=weekday)
28
+            if not use_old or not os.path.isfile(temp_fname):
29
+                try:
30
+                    urllib.request.urlretrieve(url, temp_fname)
31
+                except urllib.error.HTTPError as e:
32
+                    print("Failed to download {url}".format(url=url))
33
+            try:
34
+                with open(temp_fname, "r", encoding="utf-8") as fin:
35
+                    data = json.load(fin)
36
+            except OSError as e:
37
+                continue
38
+            current_day_foods = []
39
+            courses = data["courses"]
40
+            for course_info in courses:
41
+                print(course_info)
42
+                if course_info["category"] != "Aamupuuro":
43
+                    food = course_info["title_fi"]
44
+                    if "properties" in course_info:
45
+                        food += " ({allergies})".format(allergies=course_info["properties"])
46
+                    current_day_foods.append(food)
47
+            week_foods[weekday-1] = current_day_foods
48
+        restaurants.append([title, open_hours, week, week_foods, info])
49
+
50
+    return restaurants