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