· 6 years ago · Mar 23, 2020, 10:10 PM
1Skip to content
2Search or jump to…
3
4Pull requests
5Issues
6Marketplace
7Explore
8
9@MarkHession
10aitsoftwaredesign
11/
12project4-MarkHession
13Private
141
1500
16 Code Issues 0 Pull requests 0 Actions Projects 0 Wiki Security Insights
17project4-MarkHession/main.py /
18@MarkHession MarkHession Interal GPS accessed, TODO: access lat/lon to main class
19d536c41 yesterday
20349 lines (278 sloc) 11.3 KB
21
22# qpy:kivy
23import json
24import os
25
26import requests
27import threading
28from kivy.app import App
29from kivy.lang import Builder
30from kivy.network.urlrequest import UrlRequest
31from kivy.properties import ObjectProperty, StringProperty
32from kivy.uix.boxlayout import BoxLayout
33from kivy.uix.floatlayout import FloatLayout
34from kivy.uix.popup import Popup
35from kivy.uix.label import Label
36from kivy.core.window import Window
37
38from kivy.uix.screenmanager import ScreenManager, Screen
39from kivy.uix.treeview import TreeViewLabel
40from plyer import notification, gps
41from plyer import vibrator
42from kivy.utils import platform
43
44from kivy.network.urlrequest import UrlRequest
45
46from kivy.core.window import Window
47
48from distance_calc import distance_calc
49
50from GPS import gpsPermission
51
52Window.clearcolor = (1, 1, 1, 1)
53#platform = platform()
54
55# api key
56api_key = 'key'
57
58if platform == 'android':
59 dns = "ip"
60else:
61 dns = "ip"
62
63
64def permission():
65 pass
66 import time
67 # gpsPermission()
68 gpsPerms = gpsPermission()
69 # print("permission checking...")
70 # print("Current location: "+gpsPerms.gps_location)
71
72 gpsPerms.build()
73
74 gpsPerms.start(8000, 1)
75 time.sleep(5)
76 #gpsPerms.on_location()
77
78 gpsPerms.stop()
79
80 ##print(list(os.walk("_python_bundle")))
81
82
83class NotificationBase():
84 def __init__(self, title='', message=''):
85 self.title = title
86 self.message = message
87
88 def notify(self):
89 ''' Echoes the message to the console '''
90 print('Notification: {}\n{}'.format(self.title, self.message))
91
92
93class NotificationAndroid(NotificationBase):
94 def notify(self):
95 ''' Displays a native Android notification '''
96 from jnius import autoclass
97 from plyer.platforms.android import activity, SDK_INT
98 AndroidString = autoclass('java.lang.String')
99 PythonActivity = autoclass('org.renpy.android.PythonActivity')
100 NotificationBuilder = autoclass('android.app.Notification$Builder')
101 Drawable = autoclass("{}.R$drawable".format(activity.getPackageName()))
102 icon = Drawable.icon
103 noti = NotificationBuilder(PythonActivity.mActivity)
104 # noti.setDefaults(Notification.DEFAULT_ALL)
105 noti.setContentTitle(AndroidString(self.title.encode('utf-8')))
106 noti.setContentText(AndroidString(self.message.encode('utf-8')))
107 noti.setSmallIcon(icon)
108 noti.setAutoCancel(True)
109 nm = PythonActivity.mActivity.getSystemService(PythonActivity.NOTIFICATION_SERVICE)
110 nm.notify(0, noti.build())
111
112
113# Default to console
114Notification = NotificationBase
115
116# Platform-specific searches
117if platform == "android":
118 Notification = NotificationAndroid
119 print("gps.py: Android detected. Requesting permissions")
120 #self.request_android_permissions()
121
122
123class MainWindow(Screen):
124 location = ObjectProperty(None)
125 reminder = ObjectProperty(None)
126 Window.softinput_mode = "below_target"
127
128 # submits reminder
129 def submit_reminder(self):
130 if (self.location.text != "") & (self.reminder.text != ""):
131 # adds to db
132 location = self.location.text.replace(" ", ",")
133 reminder = self.reminder.text.replace(" ", "_")
134 req = UrlRequest(
135 dns + 'addreminder?reminder=' + reminder + '&location=' +
136 location,
137 req_body='POST')
138 req.wait()
139
140 print("submitted bruh2")
141
142 # clears text fields
143 self.location.text = ""
144 self.reminder.text = ""
145 #Notification(title="Remind Me", message="Reminder Set!").notify()
146 notification.notify(title="Remind Me")
147
148
149class SecondWindow(Screen):
150 listReminders = ObjectProperty(None)
151 listLocations = ObjectProperty(None)
152 deleteID = ObjectProperty(None)
153
154 Window.softinput_mode = "below_target"
155
156 def show_reminders(self, *args):
157 self.listReminders.text = ""
158 # ip for home wifi
159
160 url = dns + 'userReminder/' + logged_in_id
161 # sending get request and saving the response as response object
162 r = requests.get(url=url)
163 data = r.json()
164 print(data)
165 # extracting location, reminder text
166 for i in range(0, len(data)):
167 location = data[i]['location']
168 reminder = data[i]['reminder_text']
169 reminderID = data[i]['reminderID']
170 reminder = reminder.replace("_", " ")
171 # TO-DO
172 # Need to do multiline and write to a line for each iteration
173 self.listReminders.text += "\nReminderID: " + str(
174 reminderID) + " || Reminder: " + reminder + " || Location: " + location
175 # self.listReminders.text += "\nReminder: " + reminder
176 # self.listLocations.text += "\nLocation: "+location
177 # self.listLocations.text += "\nLocation: " + location
178 # printing the output
179 print("\nLocation:%s\nReminder:%s\nID:%s"
180 % (location, reminder, reminderID))
181
182 def clear_reminder_list(self):
183 self.listReminders.text = ""
184
185 def delete_reminders(self):
186 self.listReminders.text = ""
187 # converting user input to type for verification
188 try:
189 deleteID = int(self.deleteID.text)
190 if isinstance(deleteID, int):
191 url = dns + 'removeReminder/' + self.deleteID.text
192 # sending get request and saving the response as response object
193 requests.delete(url=url)
194 self.deleteID.text = ""
195 SecondWindow.show_reminders(self)
196 print("Success")
197 else:
198 self.DeleteIDPopup()
199 self.deleteID.text = ""
200 except:
201 print("An exception occurred")
202 self.DeleteIDPopup()
203 self.deleteID.text = ""
204
205 def DeleteIDPopup(self):
206 pop = Popup(title='ID',
207 content=Label(text='Input must be a whole number!'),
208 size_hint=(None, None), size=(400, 400))
209 pop.open()
210
211
212class LoginScreen(Screen):
213 email = ObjectProperty(None)
214 UserID = ObjectProperty(None)
215
216 Window.softinput_mode = "below_target"
217
218 def loginBtn(self):
219 # url = dns + 'logincheck/' + self.userID.text + '/' + self.email.text
220 url = dns + 'logincheck/' + self.userID.text + '/' + self.email.text
221 req = UrlRequest(url)
222 req.wait()
223 parsed_json = (json.dumps(req.result))
224 print("parsed json= " + parsed_json)
225 if self.userID.text == "" or self.email.text == "":
226 invalidLogin()
227 print("not valid")
228 elif parsed_json != "null":
229 kv.current = "main"
230 else:
231 invalidLogin()
232 print("not valid")
233
234 def createAccountBtn(self):
235 if self.email.text == "":
236 invalidAccount()
237 print("not valid")
238 else:
239 req = UrlRequest(dns + 'adduser?email=' + self.email.text, req_body='POST')
240 req.wait()
241 self.IdPopup()
242
243 def getuserId(self):
244 req = UrlRequest(dns + 'finduserid/' + self.email.text)
245 req.wait()
246 parsed_json = (json.dumps(req.result))
247 return parsed_json
248
249 def IdPopup(self):
250 pop = Popup(title='ID',
251 content=Label(text='Remember your ID, it is used for login. \nID: ' + self.getuserId()),
252 size_hint=(None, None), size=(400, 400))
253 pop.open()
254
255
256class WindowManager(ScreenManager):
257 pass
258
259
260def invalidLogin():
261 pop = Popup(title='Invalid Login',
262 content=Label(text='Invalid email or ID.'),
263 size_hint=(None, None), size=(400, 400))
264 pop.open()
265
266
267def invalidAccount():
268 pop = Popup(title='Invalid Account Details',
269 content=Label(text='Invalid email.'),
270 size_hint=(None, None), size=(400, 400))
271 pop.open()
272
273
274kv = Builder.load_file("my.kv")
275# db = DataBase("reminders.txt")
276
277# hard coded logged in ID - dev purpose
278logged_in_id = "1"
279
280
281def current_location():
282 URL = 'https://www.googleapis.com/geolocation/v1/geolocate?key=' + api_key
283
284 r = requests.post(url=URL)
285 data = r.json()
286 # extracting latitude, longitude and formatted address
287 # of the first matching location
288 latitude = data['location']['lat']
289 longitude = data['location']['lng']
290
291 # printing the output
292 # print("Latitude:%s\nLongitude:%s"
293 # % (latitude, longitude))
294
295 return latitude, longitude
296
297
298# thread for printing users current coords every X seconds/minutes
299def print_location():
300 # threading.Timer(10.0, print_location).start() # called every 10 seconds
301 notification.notify(title="Kivy Reminder", message="Your location is;:" + str(current_location()),
302 app_name="RemindMe")
303
304
305def pull_reminders():
306 threading.Timer(90.0, pull_reminders).start() # called every 90 seconds
307 if logged_in_id != 0:
308 url = dns + 'userReminder/' + logged_in_id
309 # sending get request and saving the response as response object
310 r = requests.get(url=url)
311 data = r.json()
312 # extracting location, reminder text
313 for i in range(0, len(data)):
314 location = data[i]['location']
315 reminder = data[i]['reminder_text']
316 # converting text location from user to co-ords
317 location_coord = location_to_coord(location)
318
319 # this calculates your current distance from any location in your reminders table and sends a notification if there is match
320 # then it deletes that triggered reminder from your table so it doesnt repeat
321 if distance_calc(current_location(), location_coord):
322 # format text for phone
323 reminder = reminder.replace("_", " ")
324 notification.notify(title="Kivy Reminder",
325 message="You have a reminder:" + str(reminder),
326 app_name="RemindMe")
327 # if platform == 'android':
328 # time = 0.5
329 # vibrator.vibrate(time=time)
330 # format text for db
331 location = location.replace(" ", ",")
332 reminder = reminder.replace(" ", "_")
333 # remove reminder with reached location from db
334 req = dns + 'removeReminder?reminder=' + reminder + '&location=' + location
335 print(req)
336 requests.delete(url=req)
337
338 # printing the output
339 # print("Location:%s\nReminder:%s\n"
340 # % (location, reminder))
341
342
343def location_to_coord(location):
344 URL = "https://maps.googleapis.com/maps/api/geocode/json"
345 # defining a params dict for the parameters to be sent to the API
346 PARAMS = {'address': location, 'key': api_key}
347 # sending get request and saving the response as response object
348 r = requests.get(url=URL, params=PARAMS)
349 # extracting data in json format
350 data = r.json()
351 # extracting latitude, longitude and formatted address
352 # of the first matching location
353 latitude = data['results'][0]['geometry']['location']['lat']
354 longitude = data['results'][0]['geometry']['location']['lng']
355 return latitude, longitude
356
357
358permission()
359# print_location()
360pull_reminders()
361
362
363class MyMainApp(App):
364 def build(self):
365
366 return kv
367
368
369if __name__ == "__main__":
370 MyMainApp().run()