/
main.py
1364 lines (1138 loc) · 47.4 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#kivy.require("1.8.0")
#Kivy Library
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.widget import Widget
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.relativelayout import RelativeLayout
from kivy.clock import Clock
from kivy.properties import StringProperty, ObjectProperty, BooleanProperty, NumericProperty
from kivy.logger import Logger
from kivy.uix.popup import Popup
from kivy import platform
from kivy.uix.checkbox import CheckBox
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.image import Image
from kivy.uix.textinput import TextInput
from kivy.adapters.listadapter import ListAdapter
from kivy.uix.listview import ListView, ListItemButton
from kivy.effects.scroll import ScrollEffect
from kivy.metrics import dp
from kivy import platform
#Graphics
from kivy.graphics import *
#Python Native
from functools import partial
from threading import Thread
import datetime
import time
import re
#Imported Source Files
import userprofile
import datamall
import datamall_bus_stop
import datadb
import netcheck
import toast
from facebook import Facebook #jnius Interpreter
#Default <Bus Service ended> text
BUS_SERVICE_ENDED = 'Not Available'
#Bus Timing Update Frequency (seconds)
UPDATE_FREQUENCY = 5
#Facebook APP ID
FACEBOOK_APP_ID = '904238149623014'
class BusInfo(FloatLayout):
def __init__(self, **kwargs):
super(BusInfo, self).__init__(**kwargs)
class DummyScrollEffect(ScrollEffect):
#ScrollEffect: Does not allow scrolling beyond the ScrollView boundaries.
#When scrolling would exceed the bounds of the ScrollView, it uses a ScrollEffect to handle the overscroll. These effects can perform actions like bouncing back, changing opacity, or simply preventing scrolling beyond the normal boundaries. Note that complex effects may perform many computations, which can be slow on weaker hardware.
#You can also create your own scroll effect by subclassing one of these, then pass it as the effect_cls in the same way.
pass
class DateTimeInfo():
def getTimeNow(self):
#Returns local time
return datetime.datetime.now().strftime("%H:%M:%S")
def getDateNow(self):
#Returns local time
return datetime.datetime.now().strftime("%Y-%m-%d")
def getUTCTime(self):
#Returns UTC Time. To calculate difference between arrival and current timings
return datetime.datetime.utcnow().strftime("%H:%M:%S")
class SearchBus(Screen):
current_labels=[]
loading_widget_collector=[]
listview_widget_collector=[]
isScreenDisabled = BooleanProperty(False)
scrolleffect = DummyScrollEffect
def on_isScreenDisabled(self, *args):
if self.isScreenDisabled:
self.ids['searchbusscreen_floatlayout'].disabled = True
else:
self.ids['searchbusscreen_floatlayout'].disabled = False
def expand_menu(self):
#Removes active header
header_label = self.ids['searchbus1']
header_placeholder = self.ids['header_placeholder']
header_searchbutton = self.ids['search_button_grid']
self.header_active = [header_label, header_placeholder, header_searchbutton]
for each_header_widget in self.header_active:
self.ids['header'].remove_widget(each_header_widget)
#Changes to active input menu
self.header_back_button = Button(
to_parent=True,
size_hint=(0.1,1),
background_normal='data/return.png',
background_down='data/return_down.png'
)
self.header_back_button.bind(on_release=self.contract_menu)
#Text Input Field Behaviour
self.header_textinput = TextInput(
to_parent=True,
size_hint=(0.9,1),
pos_hint={"top":1,"left":1},
height='120dp',
multiline=False,
cursor_blink=True,
cursor_color=(1,1,1,1),
foreground_color=(1,1,1,1),
hint_text_color=(1,1,1,0.7),
hint_text='Search a bus stop number',
font_size='24sp',
background_active='data/text_input_focus.png',
background_normal='data/text_input.png'
)
#on_text behaviour
self.header_textinput.bind(text=self.on_text)
#on validate key behaviour
self.header_textinput.bind(on_text_validate=self.start_search)
self.header_inactive = [self.header_back_button, self.header_textinput]
for each_header_widget in self.header_inactive:
self.ids['header'].add_widget(each_header_widget)
#Sets focus to the text input (updates in the next frame, or it will not work. This is a getaround)
Clock.schedule_once(self.focus_on_textinput,0)
def contract_menu(self, *args):
#removes inactive header
for each_header_widget in self.header_inactive:
self.ids['header'].remove_widget(each_header_widget)
#removes the listview if exists
if self.listview_widget_collector:
for each_listview_widget in self.listview_widget_collector:
self.ids['searchbusscreen_floatlayout'].remove_widget(self.listview_widget_collector.pop())
#restores active header
for each_header_widget in self.header_active:
self.ids['header'].add_widget(each_header_widget)
def focus_on_textinput(self, *args):
self.header_textinput.focus = True
#Suggested Bus stops
def on_text(self, *args):
#get text field text
text_input_value = self.header_textinput.text
#once user has type 3 letters and more, start substring search
if len(text_input_value)>2:
#if previous listview exists, remove it
self.closeListView()
#start search, put the response data in a list adapter
suggestions = app.datamall_bus_stop.busnamesubstringSearch(text_input_value)
#ListitemButton Behaviour
args_converter = lambda row_index, rec: {
'text':rec['text'],
'size_hint':(None,None),
'height': '50dp',
'width': self.header_textinput.width
}
suggestion_listadapter = ListAdapter(
data=suggestions,
args_converter=args_converter,
selection_mode='multiple',
selection_limit=1,
allow_empty_selection=True,
cls=ListItemButton
)
#binds each listview button to the autofill function
suggestion_listadapter.bind(on_selection_change=self.selection_change)
#Logger.info("heightheight"+str(dp(60)))
#Logger.info("heightheight"+str(float(dp(50)*len(suggestions)/self.height)))
self.suggestion_listview = ListView(
adapter=suggestion_listadapter,
size_hint_y=(float(dp(50)*len(suggestions)/self.height)) if (float(dp(50)*len(suggestions)/self.height))<0.4 else 0.4,
width=self.header_textinput.width,
pos_hint={"top":(self.height-self.header_textinput.height*1.3)/self.height},
x=self.header_textinput.x
)
#The container is a GridLayout widget held within a ScrollView widget.
#So we are giving the ScrollViewParent a custom scroll effect
#ListView >> ScrollView >> GridLayout
#effect_cls is an ObjectProperty and defaults to DampedScrollEffect.
self.suggestion_listview.container.parent.effect_cls = self.scrolleffect
#Timeout allowed to trigger the scroll_distance, in milliseconds. If the user has not moved scroll_distance within the timeout, the scrolling will be disabled, and the touch event will go to the children.
self.suggestion_listview.container.parent.scroll_distance = 10
self.suggestion_listview.container.parent.scroll_timeout = 1000
self.listview_widget_collector.append(self.suggestion_listview)
self.ids['searchbusscreen_floatlayout'].add_widget(self.suggestion_listview)
else:
#User is deleting his input, so naturally, we shall close the listview (if it exists)
self.closeListView()
#user touches a suggestion
def selection_change(self, *args):
selected_item = args[0].selection[0]
#Logger.info("busstopselection"+str(selected_item.text))
#On First Selection or when the textinput is not the same as the option selected
#Auto fills the text input widget
if selected_item.text != self.header_textinput.text:
self.header_textinput.text = selected_item.text
#On Second Selection + color change
#If text field is the same as the text in the selection, close the listview and start the search
else:
self.start_search()
def getBusStopNamefromCode(self, _busstopcode):
return app.datamall_bus_stop.getBusStopName(_busstopcode)
def closeListView(self):
#close the suggestion listview (if any)
if self.listview_widget_collector:
for each_listview in self.listview_widget_collector:
self.ids['searchbusscreen_floatlayout'].remove_widget(self.listview_widget_collector.pop())
#search text input accepts strings and numbers
def start_search(self, *args):
#if listview is active, close it
self.closeListView()
self.getUserInput()
self.contract_menu()
self.searchUserInput()
#Gets user input from the text fields busStopNoInput & busNoInput
def getUserInput(self, *args):
self._busnoinput = ''
#If search value is a number
if self.header_textinput.text.isdigit():
self._busstopnoinput = self.header_textinput.text
#if the string is not a digit
else:
response_busstopcode = app.datamall_bus_stop.searchBusStopCode(self.header_textinput.text)
#if response is not None
if response_busstopcode:
self._busstopnoinput = response_busstopcode
#not a valid bus stop. Are we gonna let it carry on first?
else:
self._busstopnoinput = self.header_textinput.text
def searchUserInput(self, *args):
#Instantiates a connection to datamall API
#Bus 911 @ a working bus stop: 46429,911/83139
app._toast('Searching for Bus Stop {}'.format(self._busstopnoinput))
#Gets list of all bus services in operation
allbuses_instance = datamall.BusInfo(self._busstopnoinput, self._busnoinput)
#Valid Bus Stop Check?
if allbuses_instance.response.status == 200:
self.busservices = allbuses_instance.getallServices()
#Removes existing labels, (if any)
if self.current_labels:
for _eachbuswidget in self.current_labels:
self.ids['searchbusscreen_gridlayout'].remove_widget(_eachbuswidget)
#Displays Loading widget
loading_widget = LoadingWidget()
self.ids['searchscreen_main_body'].add_widget(loading_widget)
self.loading_widget_collector.append(loading_widget)
#Disables main body
self.isScreenDisabled = True
#Get user preferences (saved buses)>>UI remains responsive now. Widgets can only be created after records are retrieved
#Retrieval of records allow for Checkboxes to be created with user's preference shown
self.retrievePreferredStops()
#invalid bus stop id or when all bus services have ceased operation
else:
app._toast('Invalid Bus Stop!')
def create_bus_instance_widgets(self, *args):
#Stop displaying loading widget
if self.loading_widget_collector:
for loading_widget in self.loading_widget_collector:
self.ids['searchscreen_main_body'].remove_widget(self.loading_widget_collector.pop())
#creates new labels and appends ref
for (eachbus) in self.busservices:
#Creates an EachBus instance for eachbus & Adds the Label instance to root. One bus service to one EachBus() instance
self.each_bus_instance = EachBus(self._busstopnoinput, eachbus['ServiceNo'])
self.eachbuswidget = self.each_bus_instance.getEachBusGridLayoutWidget()
#append to the current_labels list
self.current_labels.append(self.eachbuswidget)
#append to the Parent Layout
self.ids['searchbusscreen_gridlayout'].add_widget(self.eachbuswidget)
#Checkbox::Binds the Boolean Property 'active' to self.on_checkbox_active()
self.each_bus_instance.getLabels()[3].bind(active=partial(self.on_checkbox_active, self.each_bus_instance.getServiceNo(), self.each_bus_instance.getBusStopID(), self.each_bus_instance.getLabels()[3]))
#Each bus's canvas instructions for loading texture
for _eachbuswidget in self.current_labels:
with _eachbuswidget.canvas.before:
#Tints and opacity can be achieved!
_eachbuswidget.canvas.opacity = 0.9
thiscanvasrect = Rectangle(pos=_eachbuswidget.pos, size=_eachbuswidget.size, source='data/bg/each_label.png')
#http://kivy.org/planet/2014/10/updating-canvas-instructions-declared-in%C2%A0python/
#on pos or size change of the GridLayout, update the position of the canvas as well!
_eachbuswidget.bind(pos=partial(self.update_label_canvas, _eachbuswidget, thiscanvasrect), size=partial(self.update_label_canvas, _eachbuswidget, thiscanvasrect))
#enables main body again
self.isScreenDisabled = False
'''
#show current bus stop name in search
busstopnamelabel = Label(
text=self.this_busstopname,
size_hint=(1,None),
height='60dp',
font_size='16sp'
)
self.current_labels.append(busstopnamelabel)
self.ids['searchbusscreen_gridlayout'].add_widget(busstopnamelabel)
'''
def update_label_canvas(self, thisbuswidget, thiscanvasrect, *args):
thiscanvasrect.pos = thisbuswidget.pos
thiscanvasrect.size = thisbuswidget.size
def retrievePreferredStops(self, *args):
#If records not retrieved
if not app.isRecordRetrieved:
#Get user preferences (saved buses). Will exit thread if user is not logged in
thread1 = Thread(target=app.getUserSaveBusRecords,args=()).start()
#thread2 starts even before thread 1 is done (if thread1 is executed)
thread2 = Thread(target=self.check_UserSaveBusRecords_if_exists,args=()).start()
def check_UserSaveBusRecords_if_exists(self,*args):
#Still retrieving records (only if logged in)
if app._facebookid:
while not app.isRecordRetrieved:
time.sleep(1)
#Retrieval done
Clock.schedule_once(self.create_bus_instance_widgets, 0)
def on_checkbox_active(self, _serviceno, _busstopid, _labelref, *args):
#If logged in and has checked this bus
if app._facebookid and _labelref.active == True:
#show saving widget
saving_widget = SavingWidget()
self.ids['searchscreen_main_body'].add_widget(saving_widget)
self.loading_widget_collector.append(saving_widget)
self.isScreenDisabled = True
#updates mySQL DB
thread = Thread(target=self.createUserSaveBusRecords, args=(_serviceno, _busstopid, _labelref)).start()
app.all_saved_busstopNo.append(_busstopid)
app.all_saved_busno.append(_serviceno)
#app._toast('Saving. Don\'t quit the app!')
#If logged in and has unchecked this bus
elif app._facebookid and not _labelref.active == True:
#show deleting widget
deleting_widget = DeletingWidget()
self.ids['searchscreen_main_body'].add_widget(deleting_widget)
self.loading_widget_collector.append(deleting_widget)
self.isScreenDisabled = True
#updates mySQL DB
thread = Thread(target=self.deleteUserSaveBusRecords, args=(_serviceno, _busstopid, _labelref)).start()
app.all_saved_busstopNo.remove(_busstopid)
app.all_saved_busno.remove(_serviceno)
#app._toast('Deleting. Don\'t quit the app!')
elif not app._facebookid:
if _labelref.active is True:
_labelref.active = False
app._toast('Please login into Facebook first')
def createUserSaveBusRecords(self, _serviceno, _busstopid, _labelref, *args):
#if the SaveBusRecords does not exist, response code of GET request is != 200
#Create a new UserSaveBusRecords
response = datadb.PostDBInfo().createUserSaveBusRecords(_serviceno, _busstopid, app._facebookid)
#Logger.info('Saving the User\'s preference' + str(response))
#We have a response from the POST request
save_complete_status_code = response.status_code
self.saveCompleted(save_complete_status_code)
def deleteUserSaveBusRecords(self, _serviceno, _busstopid, _labelref, *args):
#Deletes a UserSaveBusRecord
response = datadb.DeleteDBInfo().deleteUserSavebusRecords(_serviceno, _busstopid, app._facebookid)
#Logger.info('Deleting the User\'s preference' + str(response))
#We have a response from the DELETE request
delete_complete_status_code = response.status_code
self.deleteCompleted(delete_complete_status_code)
def saveCompleted(self, save_complete_status_code, *args):
Clock.schedule_once(partial(self.showSaveCompletedToast, save_complete_status_code), 0)
def showSaveCompletedToast(self, save_complete_status_code, *args):
#Response for POST is 200
if save_complete_status_code==200:
#Remove Saving now widget
if self.loading_widget_collector:
for each_saving_widget in self.loading_widget_collector:
self.ids['searchscreen_main_body'].remove_widget(self.loading_widget_collector.pop())
app._toast('Saved!')
self.isScreenDisabled = False
else:
app._toast('Can\'t save! Error Code: {}'.format(str(self.save_complete)))
def deleteCompleted(self, delete_complete_status_code, *args):
Clock.schedule_once(partial(self.showDeleteCompletedToast, delete_complete_status_code), 0)
def showDeleteCompletedToast(self, delete_complete_status_code, *args):
#Response for DELETE is 200
if delete_complete_status_code==200:
#Remove Deleting now widget
if self.loading_widget_collector:
#Updates widget Label
for each_deleting_widget in self.loading_widget_collector:
self.ids['searchscreen_main_body'].remove_widget(self.loading_widget_collector.pop())
app._toast('Deleted!')
self.isScreenDisabled = False
else:
app._toast('Can\'t delete! Error Code: {}'.format(str(self.delete_complete)))
#Contains the instance for Each bus
class EachBus():
#Creates all the labels upon initialization
#disable size hint for height because of the ScrollView
#size hint for width is still available
def __init__(self, _busstopid, _serviceno, *args):
self._busstopid = _busstopid
self._serviceno = _serviceno
#creates the nextbustime instance
self.nextbustimelabel = Label(
font_size='16sp',
text=self.getBusTime(0),
size_hint=(0.35,None),
height=60
)
self.nextbusloadlabel = Label(
font_size='12sp',
text=self.getNextBusLoad(),
size_hint=(0.35,None),
height=90,
halign='center'
)
#to wrap text size according to the label size
self.nextbusloadlabel.text_size = self.nextbusloadlabel.size
#creates the subsequentbustime instance
self.subsequentbustimelabel = Label(
font_size='16sp',
text=self.getBusTime(1),
size_hint=(0.35,None),
height=60
)
self.subsequentbusloadlabel = Label(
font_size='12sp',
text=self.getSubsequentBusLoad(),
size_hint=(0.35,None),
height=90,
halign='center'
)
#to wrap text size according to the label size
self.subsequentbusloadlabel.text_size = self.subsequentbusloadlabel.size
#Creates the service number instance
self.servicenolabel = Label(
font_size='35sp',
text=self.getServiceNo(),
size_hint=(0.15,None),
height=60,
padding_y='18dp'
)
#Creates the save bus checkbox
saved_status = False
#checks if the user has saved this bus
if app.all_saved_busstopNo and app.all_saved_busno:
if (self._busstopid,self._serviceno) in zip(app.all_saved_busstopNo, app.all_saved_busno):
saved_status=True
self.savebuscheckbox = CheckBox(
size_hint=(0.15,None),
active=saved_status,
height='30dp',
background_checkbox_normal='data/checkbox_disabled_down.png',
background_checkbox_down='data/checkbox_down.png',
background_checkbox_disabled_normal='data/checkbox_disabled_normal.png',
background_checkbox_disabled_down='data/checkbox_normal.png'
)
#dummy labels to fill up GridLayout's column 1 and 4
self.dummylabel1 = Label(
size_hint=(0.15,None),
height=90
)
self.dummylabel2 = Label(
size_hint=(0.15,None),
height=90
)
#GridLayout to contain each bus's information
self.gridlayout = GridLayout(
cols=4,
rows=3,
size_hint=(1,None),
height=(self.nextbustimelabel.height+self.dummylabel1.height)*2,
padding=('25dp','15dp','15dp','10dp'),
spacing=(0,'10dp')
)
for each_bus_label in self.getLabels():
self.gridlayout.add_widget(each_bus_label)
def getBusTime(self, which_bus):
#which_bus can be either getNextTiming or getSubsequentTiming
which_bus_timing = ['getNextTiming', 'getSubsequentTiming']
try:
#Creates a GET request instance
self.busInstance = datamall.BusInfo(self._busstopid,self._serviceno)
#Gets Data
self.busInstance.scrapeBusInfo()
dateTime = getattr(self.busInstance, which_bus_timing[which_bus])()
#Finds the time
grabTime = re.findall('[0-9]+\D[0-9]+\D[0-9]+', dateTime)
#grabTime[0]==date #grabTime[1]==time(UTC)
timedelta = datetime.datetime.strptime(grabTime[1],"%H:%M:%S") - datetime.datetime.strptime(DateTimeInfo().getUTCTime(),"%H:%M:%S")
timeLeft = re.split(r'\D',str(timedelta))
if dateTime:
#timeLeft[0] can return null at times
if not (timeLeft[0]):
timeLeft[0]=0
#return minutes and seconds
#return '%s MINUTES %s SECONDS' %(str(int(timeLeft[0])*60+int(timeLeft[1])),timeLeft[2])
#return minutes only
return '%s mins' %(str(int(timeLeft[0])*60+int(timeLeft[1])))
except TypeError as e:
return BUS_SERVICE_ENDED
#Gets Bus Stop ID and Service number that is in request
def getBusStopID(self):
return self.busInstance.getbusStopID()
def getServiceNo(self):
return self.busInstance.getServiceNo()
def getNextBusLoad(self):
return self.busInstance.getNextLoad()
def getSubsequentBusLoad(self):
return self.busInstance.getSubsequentLoad()
#Gets the Label object
def getLabels(self):
self.alllabels=[self.servicenolabel,
self.nextbustimelabel,
self.subsequentbustimelabel,
self.savebuscheckbox,
self.dummylabel1,
self.nextbusloadlabel,
self.subsequentbusloadlabel,
self.dummylabel2]
return self.alllabels
def getEachBusGridLayoutWidget(self):
return self.gridlayout
class PreferredStops(Screen):
#For widget 'garbage collection'
widget_garbage_collector = []
loading_widget_collector = []
#Show 'PULL DOWN TO REFRESH?' Boolean
showInstruction = BooleanProperty(False)
is_reloading = False
is_firstload = True
isScreenDisabled = BooleanProperty(False)
def on_pre_enter(self, *args):
#Update Footer Buttons on enter
self.ids['footer'].ids['footer_saved_button'].ids['footer_saved_button_image'].source = 'data/Save_inactive.png'
#auto load on open
if self.is_firstload:
self.startFirstSearch()
self.is_firstload = False
def on_isScreenDisabled(self, *args):
if self.isScreenDisabled:
self.ids['preferredstops_mainbody'].disabled = True
else:
self.ids['preferredstops_mainbody'].disabled = False
#Defines the behaviour of the Search Button
def startFirstSearch(self, *args):
loadingwidget = LoadingWidget()
#On first run, display the loading widget while we retrieve data
self.ids['preferredstops_mainbody'].add_widget(loadingwidget)
self.loading_widget_collector.append(loadingwidget)
#Disable
self.isScreenDisabled=True
#Starts the widget creation process
self.createPreferredStops()
#Because the GET requests are significantly slow, we use threads to prevent the UI from being unresponsive
#We use these threads to schedule the widgets to be displayed once all the GET retrievals are completed
#Event Dispatcher will subsequently run the callback functions to display the widgets
def createPreferredStops(self, *args):
#If records have not been retrieved or if user has no saved buses
if not app.all_saved_busstopNo and not app.all_saved_busno:
#Get user preferences (saved buses)
self.isthread1_done = False
thread1 = Thread(target=self.getUserSaveBusRecords,args=()).start()
#If records have already been retrieved and saved locally
if app.all_saved_busstopNo and app.all_saved_busno:
self.isthread1_done = True
#Checks if thread 1 is done. If done, create the preference instances
thread2 = Thread(target=self.checkUserSaveBusRecords_if_exist,args=()).start()
#Displays all the saved widgets
def showPreferredStops(self, *args):
#If existing records exist
if app.all_saved_busstopNo and app.all_saved_busno:
for each_saved_busstopNo,each_saved_busno in zip(app.all_saved_busstopNo, app.all_saved_busno):
eachSavedPreference_instance = EachSavedPreference(each_saved_busstopNo, each_saved_busno)
#Add the GridLayout to the ScrollView
self.ids['preferredstops_body'].add_widget(eachSavedPreference_instance.getGridLayout())
#Saves the reference of each GridLayout so that we can remove later
self.widget_garbage_collector.append(eachSavedPreference_instance.getGridLayout())
#Another loop to create the canvas for each entry
for _each_saved_widget in self.widget_garbage_collector:
with _each_saved_widget.canvas.before:
_each_saved_widget.canvas.opacity = 0.9
thiscanvasrect = Rectangle(
pos=_each_saved_widget.pos,
size=_each_saved_widget.size,
source='data/bg/each_label.png'
)
_each_saved_widget.bind(
pos=partial(self.update_canvas, _each_saved_widget, thiscanvasrect),
size=partial(self.update_canvas, _each_saved_widget, thiscanvasrect)
)
#if no records exists, do something
def update_canvas(self, thiswidget, thiscanvasrect, *args):
thiscanvasrect.pos = thiswidget.pos
thiscanvasrect.size = thiswidget.size
#'Garbage' Collection of all displayed widgets, if any
def removePreferredStops(self, *args):
#If loading widget is active, remove it.
if self.loading_widget_collector:
for each_loading_widget in self.loading_widget_collector:
self.ids['preferredstops_mainbody'].remove_widget(self.loading_widget_collector.pop())
#Removes previous instances (IF ANY)
if self.widget_garbage_collector:
for each_Grid in self.widget_garbage_collector:
self.ids['preferredstops_body'].remove_widget(self.widget_garbage_collector.pop())
#GET Request from RESTful API: DreamFactory
def getUserSaveBusRecords(self):
userSaveBusRecords = app.getUserSaveBusRecords()
self.isthread1_done = True
#return userSaveBusRecords
def checkUserSaveBusRecords_if_exist(self, *args):
#still waiting for thread 1
while not self.isthread1_done:
time.sleep(1)
#Removes scroll lock if reloading
if self.is_reloading:
self.ids['preferred_scroll_view'].do_scroll_y = True
#Enable the screen again
self.isScreenDisabled = False
#check is done, remove old widgets
Clock.schedule_once(self.removePreferredStops,0)
#displays new widgets
Clock.schedule_once(self.showPreferredStops, 0)
#Pull to refresh Behaviour
def pullToRefresh(self, scr_val):
#Large overscroll. The gap between slight scroll and this must be significant. Else, the user could have missed slight scroll activity
if scr_val>1.05:
self.is_reloading = True
#Slight overscroll activity
elif (scr_val>1.02):
#shows 'pull down to refresh' instructions
if not self.showInstruction and not self.is_reloading:
self.showInstruction = True
#User Release after refreshing
if self.showInstruction and self.is_reloading:
#Lock Scroll
self.ids['preferred_scroll_view'].do_scroll_y = False
self.start_refresh()
#No overscroll activity
else:
self.is_reloading = False
if self.showInstruction:
self.showInstruction = False
def start_refresh(self):
#Show Loading widget
loadingwidget = LoadingWidget()
self.ids['preferredstops_mainbody'].add_widget(loadingwidget)
self.loading_widget_collector.append(loadingwidget)
#Disable the mainbody
self.isScreenDisabled = True
#Call for widget update. Once the widgets are ready, the scroll lock is removed by self.createPreferredStops()
self.createPreferredStops()
#Label will be auto removed
def on_showInstruction(self, *args):
#if user is pulling down
if self.showInstruction:
hiddenwidgets = self.ids['preferredstops_body']
self.ids['main_body'].remove_widget(self.ids['preferredstops_body'])
#show instructions
self.instructions_label = Label(text='[b]PULL DOWN TO REFRESH[/b]', markup=True)
self.ids['main_body'].add_widget(self.instructions_label)
self.ids['main_body'].add_widget(hiddenwidgets)
#if user is not pulling down anymore
elif not self.showInstruction:
#hide instructions
self.ids['main_body'].remove_widget(self.instructions_label)
class EachSavedPreference():
def __init__(self, _busstopid, _serviceno, *args):
#Local variables
self._busstopid = _busstopid
self._serviceno = _serviceno
#All the required Labels
self.bus_stop_name = Label(
text='[b]{}[/b]'.format(str(self.getBusStopName(str(_busstopid)))),
size_hint=(1,None),
height='30dp',
markup=True,
font_size='15sp'
)
self.bus_stop_text = Label(
text='BUS STOP',
size_hint=(1,None),
height='20dp'
)
self.bus_stop_label = Label(
text=_busstopid,
size_hint=(1,None),
height='20sp'
)
self.service_no_label = Label(
text='[b]{}[/b]'.format(_serviceno),
font_size='35sp',
size_hint=(1,None),
height='60dp',
markup=True
)
self.next_bus_text = Label(
text='NEXT BUS',
size_hint=(1,None),
height='60dp'
)
self.subsequent_bus_text = Label(
text='SUBSEQUENT BUS',
size_hint=(1,None),
height='60dp'
)
self.next_arrival_label = Label(
text=self.getBusTime(0),
size_hint=(1,None),
height='25dp',
font_size='20sp',
valign='top'
)
self.subsequent_arrival_label = Label(
text=self.getBusTime(1),
size_hint=(1,None),
height='25dp',
font_size='20sp',
valign='top'
)
self.next_load_label = Label(
text=self.getNextBusLoad(),
size_hint=(1,None),
height='50dp'
)
self.subsequent_load_label = Label(
text=self.getSubsequentBusLoad(),
size_hint=(1,None),
height='50dp'
)
#Grouping in Grid 0
self.grid0_labels = [self.bus_stop_name]
#Grouping in Grid 1
self.grid1_labels = [self.bus_stop_text, self.bus_stop_label]
#Grouping in Grid 2
self.grid2_labels = [self.service_no_label]
#Grouping in Grid 3 follows the arrangement as shown below
self.grid3_labels = [self.next_bus_text, self.subsequent_bus_text,
self.next_arrival_label, self.subsequent_arrival_label,
self.next_load_label, self.subsequent_load_label]
#Creating the Layout (Made up of 3 GridLayouts)
self.grid0 = GridLayout(cols=1, size_hint=(1,None),height=self.bus_stop_name.height)
self.grid1 = GridLayout(cols=2, size_hint=(1,None),height=self.bus_stop_text.height)
self.grid2 = GridLayout(cols=1, size_hint=(1,None), height=self.service_no_label.height)
self.grid3 = GridLayout(cols=2, rows=3, size_hint=(1,None), height=(self.next_bus_text.height+self.next_arrival_label.height+self.next_load_label.height)*1.2)
#Adding the Labels to each GridLayout
for each_grid0_label in self.grid0_labels:
self.grid0.add_widget(each_grid0_label)
for each_grid1_label in self.grid1_labels:
self.grid1.add_widget(each_grid1_label)
for each_grid2_label in self.grid2_labels:
self.grid2.add_widget(each_grid2_label)
for each_grid3_label in self.grid3_labels:
self.grid3.add_widget(each_grid3_label)
self.mainGrid = GridLayout(
cols=1,
size_hint=(1,None),
height=(self.grid0.height+self.grid1.height+self.grid2.height+self.grid3.height),
padding=('15dp','15dp','15dp','15dp')
)
self.mainGrid.add_widget(self.grid0)
self.mainGrid.add_widget(self.grid1)
self.mainGrid.add_widget(self.grid2)
self.mainGrid.add_widget(self.grid3)
def getBusTime(self, which_bus):
#which_bus can be either getNextTiming or getSubsequentTiming
which_bus_timing = ['getNextTiming', 'getSubsequentTiming']
try:
#Creates a GET request instance
self.busInstance = datamall.BusInfo(self._busstopid, self._serviceno)
#Gets Data
self.busInstance.scrapeBusInfo()
dateTime = getattr(self.busInstance, which_bus_timing[which_bus])()
#Finds the time
grabTime = re.findall('[0-9]+\D[0-9]+\D[0-9]+', dateTime)
#grabTime[0]==date #grabTime[1]==time(UTC)
timedelta = datetime.datetime.strptime(grabTime[1],"%H:%M:%S") - datetime.datetime.strptime(DateTimeInfo().getUTCTime(),"%H:%M:%S")
timeLeft = re.split(r'\D',str(timedelta))
if dateTime:
#timeLeft[0] can return null at times
if not (timeLeft[0]):
timeLeft[0]=0
#return minutes and seconds
#return '%s MINUTES %s SECONDS' %(str(int(timeLeft[0])*60+int(timeLeft[1])),timeLeft[2])
#return minutes only
return '%s mins' %(str(int(timeLeft[0])*60+int(timeLeft[1])))
except TypeError as e:
return BUS_SERVICE_ENDED
except KeyError as e:
return BUS_SERVICE_ENDED
def getNextBusLoad(self):
return self.busInstance.getNextLoad()
def getSubsequentBusLoad(self):
return self.busInstance.getSubsequentLoad()
def getBusStopName(self, _busstop_id):
return app.datamall_bus_stop.getBusStopName(str(_busstop_id))
def getGridLayout(self):
return self.mainGrid
class FacebookUI_Existing_User(Screen):
def on_pre_enter(self, *args):
#updates footer button on enter
self.ids['footer'].ids['footer_accountsettings_button'].ids['footer_accountsettings_button_image'].source = 'data/User Accounts inactive.png'
self.ids.labelAccountID.text = app._facebookid
def launchPopup(self, title):
popupContent = askConfirmation()
popupContent.setText(title, popupContent)
popup = Popup(title=title, content=popupContent, size_hint=(0.8,0.3), auto_dismiss=False)
self.btnYesBehaviour(title, popupContent, popup)
#Binds cancel button to dismiss activity
popupContent.ids.btnDismiss.bind(on_press=popup.dismiss)
popup.open()
def btnYesBehaviour(self, title, popupContent, popup):
if (title=="Logout"):
#Binds the yes button to the LOGOUT activity
popupContent.ids.btnYes.bind(on_press=partial(self.logoutUser, popup))
elif (title=="Reset"):
#Bind the yes button to the RESET activity
popupContent.ids.btnYes.bind(on_press=partial(self.resetUser, popup))
def logoutUser(self, popup, *args):
app._toast('You are now logged out')
popup.dismiss()
#Deletes the save file
app.fb_userprofile.removeUSER()
#Transfer to the main screen
app.root_widget.current = 'accountsettings'
def resetUser(self, popup, *args):
app._toast('Deleting your records')
popup.dismiss()
#Deletes all the user saved buses using FB ID as a filter
response = datadb.DeleteDBInfo().deleteAllUserRecords(app._facebookid)
if (response.status_code == 200):
app._toast('Your account has been reset')
app.all_saved_busstopNo = []
app.all_saved_busno = []
else:
app._toast('Something went wrong. Cannot reset your account')
class askConfirmation(RelativeLayout):
def setText(self, title, popup):
if (title=="Logout"):
self.ids.labelText.text = "Do you really want to LOGOUT?"
elif (title=="Reset"):
self.ids.labelText.text = "Are you sure that you want to RESET your account?"
class BusTimingScreen(Screen):
#TEST VARIABLES
_busstopid = 46429
_serviceno = 911
def getNextBusTime(self):
Clock.schedule_once(self.updateNextBusTime,UPDATE_FREQUENCY)
try:
self.busInstance = datamall.BusInfo(self._busstopid,self._serviceno)
self.busInstance.scrapeBusInfo()
dateTime = self.busInstance.getNextTiming()
grabTime = re.findall('[0-9]+\D[0-9]+\D[0-9]+',dateTime)
#grabTime[0]==date #grabTime[1]==time(UTC)
timedelta = datetime.datetime.strptime(grabTime[1],"%H:%M:%S") - datetime.datetime.strptime(DateTimeInfo().getUTCTime(),"%H:%M:%S")
timeLeft = re.split(r'\D',str(timedelta))
if dateTime:
#timeLeft[0] can return null at times
if not (timeLeft[0]):
timeLeft[0]=0
return '%s MINUTES %s SECONDS' %(str(int(timeLeft[0])*60+int(timeLeft[1])),timeLeft[2])
except TypeError:
return BUS_SERVICE_ENDED