Exemplo n.º 1
0
    def build(self):
        screen = Screen()
        self.theme_cls.theme_style = "Light"
        self.helper_string = Builder.load_string(code_helper)
        screen.add_widget(self.helper_string)
        self.skip_target_view = MDTapTargetView(
            widget=self.helper_string.get_screen(
                'firstwelcome').ids.welcome_skip,
            title_text="Next",
            widget_position="left_bottom",
            title_text_size="20sp",
            description_text="GO next",
            outer_radius='80dp',
            description_text_color=[1, 0, 0, 0],
            outer_circle_alpha=0.40,
            target_radius='40dp')
        self.android_target_view = MDTapTargetView(
            widget=self.helper_string.get_screen(
                'androidinfo').ids.android_info,
            title_text="Hey!!",
            widget_position="center",
            title_text_size="20sp",
            title_position="right_top",
            description_text="I am your assistant\nClick on me",
            outer_radius='180dp',
            description_text_color=[0, 0, 0, 1],
            outer_circle_alpha=0.5,
            target_radius='50dp')
        self.skip_target_view.start()
        self.android_target_view.start()

        #self.dob initialize
        self.dob_entered = True
        return screen
Exemplo n.º 2
0
class DemoApp(MDApp):
    def build(self):
        screen = Screen()

        self.help_str = Builder.load_string(helper_string)

        screen.add_widget(self.help_str)
        self.taptarget = MDTapTargetView(
            widget=self.help_str.get_screen('bye').ids.textview,
            title_text='text',
            widget_position='left_bottom',
            title_text_size='20sp',
            description_text="GO next",
            outer_radius='80dp',
            description_text_color=[1, 0, 0, 0],
            outer_circle_alpha=0.40,
            target_radius='40dp')
        return screen

    def open_tapview(self):
        self.taptarget.start()

    def close_tapview(self):
        self.taptarget.stop()
        self.help_str.get_screen('bye').ids.next.disabled = False
Exemplo n.º 3
0
class AnotherScreen(Screen):
    def __init__(self, **kw):
        super().__init__(**kw)
        self.button = ObjectProperty(None)
        self.tap_target_view = MDTapTargetView(
            outer_circle_color=(1, 1, 1),
            widget=self.ids.button,
            title_text="    tutorials",
            draw_shadow=True,
            title_text_size=50,
            title_text_color=(255, 255, 0, 1),
            widget_position="right_top",
            description_text=
            "  most part of our\n  life is always wasted \n    due to lack of knowledge",
            description_text_color=(100, 100, 0, 1),
        )

    def monk(self):
        if self.tap_target_view.state == "close":
            self.tap_target_view.start()
        else:
            self.tap_target_view.stop()

    def lonk(self):
        p = monk()
        self.add_widget(p)

    def rongr(self):
        print("hi")
Exemplo n.º 4
0
 def build(self):
     screen = Builder.load_string(KV)
     self.tap_target_view = MDTapTargetView(
         widget=screen.ids.button,
         title_text="Lire",
         description_text="Patientez en écoutant la lecture de ce texte",
         widget_position="left_bottom",
     )
     return screen
Exemplo n.º 5
0
    def build(self):

        #Accessing settings database
        cur.execute("SELECT mode from settings where attribute='darkmode' ")
        GpsHelper().run()
        #App theme and UI color schemes
        darkmode_opt_list = cur.fetchall()
        darkmode_opt = darkmode_opt_list[0][0]
        self.theme_cls.primary_palette = "Cyan"
        self.theme_cls.primary_hue = "800"
        self.theme_cls.accent_palette = "Gray"
        self.theme_cls.accent_hue = "50"
        self.search_menu = SearchPopupMenu()

        self.tap_target_view = MDTapTargetView(
            widget=self.root.ids.button,
            title_text="Click here to locate you.",
            description_text="Make sure we are right over you",
            widget_position="left_bottom",
        )
        if darkmode_opt == "on":
            print("dark mode on")
            self.theme_cls.theme_style = "Dark"
            self.root.ids.darkmode_switch.active = True
        else:
            print("light mode on")
            self.theme_cls.theme_style = "Light"
            self.root.ids.darkmode_switch.active = False

        if logged_in == True:
            self.root.ids.manager.current = "Home"
            self.root.ids.ecomap.add_marker(MapMarker(lat=60, lon=30))
            myloc = MapMarker(lat=30.3433, lon=77.8839)
            self.root.ids.ecomap.add_marker(myloc)

            def repos(button):
                self.root.ids.ecomap.center_on(31.901303405681098, 76.5568)
                self.root.ids.ecomap.zoom = 18

            self.tap_target_view.bind(on_close=repos)

            def drop_marker_db(button):
                pass
                # temp_marker = MapMarker(lat=val[0], lon=val[1])
                # screen.ids.ecomap.add_marker(temp_marker)

            try:
                self.start_anim.cancel()
            except:
                pass
            self.start_anim = Clock.schedule_once(self.start_tp_anim, 3.5)

        elif logged_in == False:
            self.root.ids.parent_manager.current = "account_setup"
Exemplo n.º 6
0
 def tap_target_start(self):
     self.tap_target_view = MDTapTargetView(
         widget=self.ids['button'],
         title_text="akria",
         description_text="what can i do for you sir?",
         widget_position="center",
         title_position="left_top",
         outer_radius=150,
     )
     if self.tap_target_view.state == "open":
         self.tap_target_view.stop()
     else:
         self.tap_target_view.start()
 def __init__(self, app):
     self.tap_1 = MDTapTargetView(
         widget=app.root.ids.MD_tap_target_view_screen.ids.button1,
         title_text='This is an MDTapTargetView',
         description_text='This is the description',
         widget_position='left_bottom',
         cancelable=True)
     self.tap_2 = MDTapTargetView(
         widget=app.root.ids.MD_tap_target_view_screen.ids.button2,
         title_text='This is an MDTapTargetView',
         description_text='This is the description',
         widget_position='right_top',
         cancelable=True)
Exemplo n.º 8
0
    def __init__(self, **kwargs):
        Builder.load_file('kvs/WelcomeScreen.kv')
        super(WelcomeScreen, self).__init__(**kwargs)

        # timeout variables
        self.timeout_event = None
        self.timeout_time = 30  # Seconds

        # connect tap-target-view
        self.tap_target_view = MDTapTargetView(
            widget=self.ids.info,
            title_text="Version Information",
            description_text=f"Build {App.get_running_app().build_version}\n",
            widget_position="right_bottom"
        )
Exemplo n.º 9
0
 def build(self):
     screen = Screen()
     self.help_str = Builder.load_string(KV)
     screen.add_widget(self.help_str)
     self.targetview = MDTapTargetView(
         widget=self.help_str.get_screen('bye').ids.t_btn,
         title_text="next",
         widget_position='left_bottom',
         title_text_size='20sp',
         description_text="go text",
         outer_radius='80dp',
         description_text_color=[1, 0, 0, 1],
         outer_circle_alpha=0.40,
         target_radius="40dp")
     return screen
Exemplo n.º 10
0
 def __init__(self, **kw):
     super().__init__(**kw)
     self.button = ObjectProperty(None)
     self.tap_target_view = MDTapTargetView(
         outer_circle_color=(1, 1, 1),
         widget=self.ids.button,
         title_text="    tutorials",
         draw_shadow=True,
         title_text_size=50,
         title_text_color=(255, 255, 0, 1),
         widget_position="right_top",
         description_text=
         "  most part of our\n  life is always wasted \n    due to lack of knowledge",
         description_text_color=(100, 100, 0, 1),
     )
Exemplo n.º 11
0
class DemoApp(MDApp):
    def build(self):
        screen = Builder.load_string(KV)
        self.tap_target_view = MDTapTargetView(
            widget=screen.ids.button,
            title_text="Lire",
            description_text="Patientez en écoutant la lecture de ce texte",
            widget_position="left_bottom",
        )
        return screen

    def tap_target_start(self):
        if self.tap_target_view.state == "close":
            self.tap_target_view.start()
        else:
            self.tap_target_view.stop()
Exemplo n.º 12
0
 def tap_target_start(self):
     if self.tap_target_view is None:
         self.tap_target_view = MDTapTargetView(
             widget=self.ids.commitTipsButton,
             widget_position="right_bottom",
             title_text="Tips for You",
             title_text_size="20sp",
             description_text=
             "After selecting a numeric values in\nthe above controls using the\nincrement or decrement "
             +
             "buttons,\nclick on the new number to\ncommit to the ventilator",
             description_text_color=[1, 1, .5, 1])
     if self.tap_target_view.state == "close":
         self.tap_target_view.start()
     else:
         self.tap_target_view.stop()
Exemplo n.º 13
0
    def build(self):
        screen = Screen()

        self.help_str = Builder.load_string(helper_string)

        screen.add_widget(self.help_str)
        self.taptarget = MDTapTargetView(
            widget=self.help_str.get_screen('bye').ids.textview,
            title_text='text',
            widget_position='left_bottom',
            title_text_size='20sp',
            description_text="GO next",
            outer_radius='80dp',
            description_text_color=[1, 0, 0, 0],
            outer_circle_alpha=0.40,
            target_radius='40dp')
        return screen
Exemplo n.º 14
0
    def on_start(self):
        """Creates a list of items with examples on start screen."""

        unsort = self.scan_list
        # print(unsort)
        if unsort:
            sort = sorted(unsort, key=lambda x: x['SPEED'], reverse=True)
            # print(sort)
            self.show_List()
            self.show_List(sort)
            self.root.ids.Tproxys.text = f"proxys: {len(sort)}"
            self.root.ids.Tscan.text = f"scan: {self.configs['totalScan']}"
        else:
            self.root.ids.Tscan.text = "scan: 0"
            self.root.ids.Tproxys.text = "proxys: 0"
        self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}"
        self.root.ids.Smirror.text = f"Mirror: {parse.urlparse(self.configs['mirror']).netloc}".upper(
        )
        # self.root.ids.backdrop._front_layer_open=True
        Logger.info(f"Platform: {platform}")
        # if platform == 'android':
        # self.ads = KivMob(adMobIds.APP)
        # self.ads.new_banner(adMobIds.BANNER, top_pos=False)
        # self.ads.request_banner()
        # self.ads.show_banner()

        # self.root.ids.adsShow.size = (self.root.ids.backdrop_front_layer.width, 110)

        self.mirrorPic()
        self.protPic()
        self.listPic()
        self.tap_target_list_view = MDTapTargetView(
            widget=self.root.ids.Slist,
            title_text="Pic a lists",
            description_text="I will remember your list later!",
            widget_position="right_top",
            # outer_radius=dp(320),
            cancelable=True,
            outer_circle_color=self.theme_cls.primary_color[:-1],
            outer_circle_alpha=0.9,
        )
        Thread(target=self.checkUpdates).start()
Exemplo n.º 15
0
 def build(self):
     self.theme_cls.theme_style = "Dark"  # "Light"
     self.theme_cls.primary_palette = "Green"  # "Purple", "Red"
     self.theme_cls.primary_hue = "A700"  # "500"
     self.theme_cls.accent_palette = 'Lime'
     speed_dial = MDFloatingActionButtonSpeedDial()
     speed_dial.hint_animation= True
     speed_dial.right_pad = True
     speed_dial.data = self.data
     speed_dial.root_button_anim = True
     screen= Builder.load_string(kv)
     screen.add_widget(speed_dial)
     self.tap_target_view = MDTapTargetView(
         widget=screen.ids.button,
         title_text="Add Trip",
         description_text="Let people know where are you heading",
         widget_position="left_bottom",
     )
     
     return screen
Exemplo n.º 16
0
class ContentNavigationDrawer(BoxLayout):
    def __init__(self, **kwargs):
        super(ContentNavigationDrawer, self).__init__(**kwargs)
        self.tap_target_view = None

    def tap_target_start(self):
        if self.tap_target_view is None:
            self.tap_target_view = MDTapTargetView(
                widget=self.ids.commitTipsButton,
                widget_position="right_bottom",
                title_text="Tips for You",
                title_text_size="20sp",
                description_text=
                "After selecting a numeric values in\nthe above controls using the\nincrement or decrement "
                +
                "buttons,\nclick on the new number to\ncommit to the ventilator",
                description_text_color=[1, 1, .5, 1])
        if self.tap_target_view.state == "close":
            self.tap_target_view.start()
        else:
            self.tap_target_view.stop()

    def numeric_buttons_callback(self, button_type=None, widget=None):
        """
        This method is called by the increment and decrement buttons in the bottom sheet of the Control Screen
        :param button_type: str value, its either 'decrement' or 'increment'
        :param widget: The widget whose text is to be updated
        :return: None
        """
        value_char = ''
        if widget.text.isdigit():
            value_digit = eval(widget.text)
        else:
            values = widget.text.split(':')
            value_char = values[0] + ':'
            value_digit = eval(values[-1])
        if button_type == 'decrement':
            value_digit -= 1
        else:
            value_digit += 1
        widget.text = value_char + str(value_digit)
Exemplo n.º 17
0
    def __init__(self, ipaddr="", **kwargs):
        super().__init__(**kwargs)
        self.dbRW = MyDb()
        self.ipaddr = ipaddr
        self.ids.ip.text, \
            self.ids.port.text = ipaddr.split(":")
        addrScnHist = self.dbRW.getAllProxyScan(ipaddr)
        from main import ProxyShowList

        for i, p in enumerate(addrScnHist):
            self.ids.md_list.add_widget(ProxyShowList(
                text=f"{agoConv(p[5])}",
                text1=f"{p[4]}",
                text2=f" {sec_to_mins(float((p[2])))}",
                text3=f" {p[1]} MB",
                text4=f" {size(p[3], system=alternative)}/s",
                _height=dp(20)
            ))
        firstTime = TrNumBool(self.dbRW.getConfig("openNo")[0], 'r', 0)
        if firstTime:
            fulladdrCopyTT = MDTapTargetView(
                widget=self.ids.adds,
                title_text="Copy IP:PORT by tapping ':'",
                description_text="That's way you can\ncopy full address \nfaster way.",  # noqa
                widget_position="left_bottom"
            )
            fulladdrCopyTT.bind(
                on_open=lambda x: self.textColorChange('o'),
                on_close=lambda x: self.textColorChange('c')
            )
            fulladdrCopyTT.start()
            self.dbRW.updateConfig("openNo", firstTime)
Exemplo n.º 18
0
class ProxySpeedTestApp(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.icon = f"{environ['KITCHEN_SINK_ASSETS']}icon.png"
        self.version = __version__
        self.theme_cls.primary_palette = "LightBlue"
        self.dialog_change_theme = None
        self.toolbar = None
        self.scaning = Queue()
        self.running = Queue()
        self.currentSpeed = Queue()

        self.pbar0 = Queue()
        self.pbar1 = Queue()
        self.pbar2 = Queue()
        self.totalpb = Queue()

        configs = dbRW.getAllConfigs()
        mirrors = dbRW.getAllMirrors()
        self.selLId = configs[0][2]

        if self.selLId:
            totalScan = dbRW.getProxysInxTS(self.selLId)[0]
            getips = dbRW.getAllCurrentProxys(self.selLId)
            protocol = getips[0][4]

        self.scan_list = []
        if self.selLId:
            for l in getips:
                if not None in l:
                    self.scan_list.append({
                        "IP": l[0],
                        "SIZE": l[1],
                        "TIME": l[2],
                        "SPEED": l[3],
                        "top3c": l[6]
                    })

        self.theme_cls.theme_style = configs[0][0]

        miInx = configs[0][1]
        self.configs = {
            'protocol': protocol if self.selLId else 'http',
            'mirror': mirrors[miInx][0],
            'timeout': int(configs[0][3]),
            'fileSize': int(configs[0][4]),
            'miInx': miInx,
            'proxysInx': [],
            'mirrors': mirrors,
            'proxys': getips if self.selLId else [],
            'totalScan': totalScan if self.selLId else 0
        }

    # def on_resume(self):
    #     self.ads.request_interstitial()

    def changeThemeMode(self, inst):
        self.theme_cls.theme_style = inst

        dbRW.updateThemeMode(inst)

    def checkUpdates(self, ava=False, d=False):
        # print(ava)
        upCURL = 'https://raw.githubusercontent.com/biplobsd/proxySpeedTestApp/master/updates.json'
        # from json import load
        # with open('updates.json', 'r') as read:
        #     updateinfo = load(read)
        # toast("Checking for any updates ...")
        try:
            updateinfo = get(upCURL).json()
        except:
            updateinfo = {
                "version": float(self.version),
                "messages": "",
                "changelogs": "",
                "force": "false",
                "release": {
                    "win": "",
                    "linux": "",
                    "android": "",
                    "macosx": "",
                    "unknown": "",
                    "kivy_build": ""
                }
            }
            # toast("Faild app update check!")
        if updateinfo:
            try:
                appLink = updateinfo["release"][platform]
            except KeyError:
                return
            title = f"App update v{updateinfo['version']}"
            msg = "You are already in latest version!"
            b1 = "CENCEL"
            force = False

            if updateinfo['version'] > float(self.version) and appLink != "":
                if updateinfo['messages']: title = updateinfo['messages']
                msg = ""
                b2 = "DOWNLOAD"
                force = bool(updateinfo['force'])
                if force:
                    b1 = "EXIT"
                ava = True
            else:
                b2 = "CHECK"

            self.updateDialog = MDDialog(
                title=title,
                text=msg + updateinfo['changelogs'] +
                f"\n\n[size=15]Force update: {force}[/size]",
                auto_dismiss=False,
                buttons=[
                    MDFlatButton(
                        text=b1,
                        text_color=self.theme_cls.primary_color,
                        on_release=lambda x: self.updateDialog.dismiss()
                        if b1 == "CENCEL" else self.stop()),
                    MDRaisedButton(
                        text=b2,
                        on_release=lambda x: open_link(appLink)
                        if b2 == "DOWNLOAD" else self.FCU(self.updateDialog),
                        text_color=self.theme_cls.primary_light,
                    ),
                ],
            )
            self.updateDialog.ids.title.theme_text_color = "Custom"
            self.updateDialog.ids.title.text_color = self.theme_cls.primary_light
            if ava: self.updateDialog.open()

    def FCU(self, inst):
        inst.dismiss()
        Clock.schedule_once(partial(self.checkUpdates, True))

    def on_pause(self):
        return True

    def save_UpdateDB(self, l=[]):
        dbRW = MyDb()
        if l: dbRW.updateScanList(l)

    def build(self):
        if platform == "android":
            self._statusBarColor()
        Builder.load_file(
            f"{environ['KITCHEN_SINK_ROOT']}/libs/kv/list_items.kv")
        Builder.load_file(
            f"{environ['KITCHEN_SINK_ROOT']}/libs/kv/dialog_change_theme.kv")

        return Builder.load_file(
            f"{environ['KITCHEN_SINK_ROOT']}/libs/kv/start_screen.kv")

    @run_on_ui_thread
    def _statusBarColor(self, color="#03A9F4"):

        window = activity.getWindow()
        window.clearFlags(WindowManager.FLAG_TRANSLUCENT_STATUS)
        window.addFlags(WindowManager.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
        window.setStatusBarColor(Color.parseColor(color))
        window.setNavigationBarColor(Color.parseColor(color))

    def show_dialog_change_theme(self):
        if not self.dialog_change_theme:
            self.dialog_change_theme = KitchenSinkDialogChangeTheme()
            self.dialog_change_theme.set_list_colors_themes()
        self.dialog_change_theme.open()

    def on_start(self):
        """Creates a list of items with examples on start screen."""

        unsort = self.scan_list
        # print(unsort)
        if unsort:
            sort = sorted(unsort, key=lambda x: x['SPEED'], reverse=True)
            # print(sort)
            self.show_List()
            self.show_List(sort)
            self.root.ids.Tproxys.text = f"proxys: {len(sort)}"
            self.root.ids.Tscan.text = f"scan: {self.configs['totalScan']}"
        else:
            self.root.ids.Tscan.text = "scan: 0"
            self.root.ids.Tproxys.text = "proxys: 0"
        self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}"
        self.root.ids.Smirror.text = f"Mirror: {parse.urlparse(self.configs['mirror']).netloc}".upper(
        )
        # self.root.ids.backdrop._front_layer_open=True
        Logger.info(f"Platform: {platform}")
        # if platform == 'android':
        # self.ads = KivMob(adMobIds.APP)
        # self.ads.new_banner(adMobIds.BANNER, top_pos=False)
        # self.ads.request_banner()
        # self.ads.show_banner()

        # self.root.ids.adsShow.size = (self.root.ids.backdrop_front_layer.width, 110)

        self.mirrorPic()
        self.protPic()
        self.listPic()
        self.tap_target_list_view = MDTapTargetView(
            widget=self.root.ids.Slist,
            title_text="Pic a lists",
            description_text="I will remember your list later!",
            widget_position="right_top",
            # outer_radius=dp(320),
            cancelable=True,
            outer_circle_color=self.theme_cls.primary_color[:-1],
            outer_circle_alpha=0.9,
        )
        Thread(target=self.checkUpdates).start()

    def listPic(self):

        proxysInx = dbRW.getProxysInx()
        self.selLId = dbRW.getConfig('proxysInx')[0]
        Logger.debug(self.selLId)
        self.configs['proxysInx'] = proxysInx

        if proxysInx:
            selLIdindxDict = {}
            self.ListItems = []
            i = 0
            for Inx in proxysInx:
                self.ListItems.append({
                    "text": f'#{i} ' + agoConv(Inx[0]),
                    "font_style": "Caption",
                    "height": "36dp",
                    "top_pad": "35dp",
                    "bot_pad": "10dp"
                })
                selLIdindxDict[Inx[0]] = i
                i += 1
        else:
            self.ListItems = [{
                "text": "None",
                "font_style": "Caption",
                "height": "36dp",
                "top_pad": "35dp",
                "bot_pad": "10dp"
            }]

        if proxysInx:
            self.selLIdindx = selLIdindxDict[self.selLId]
        self.root.ids.Slist.text = f"list : #{self.selLIdindx} {agoConv(self.selLId)}".upper(
        ) if proxysInx else "list :"

        self.listSel = MDDropdownMenu(
            caller=self.root.ids.Slist,
            items=self.ListItems,
            width_mult=4,
            opening_time=0.2,
            position='auto',
            max_height=0,
            selected_color=self.theme_cls.primary_dark_hue)
        self.listSel.bind(on_release=self.set_list,
                          on_dismiss=self.manuDismiss)

    def manuDismiss(self, ins):
        ins.caller.custom_color = get_color_from_hex(
            colors[self.theme_cls.primary_palette]["300"])

    def set_list(self, insMain, ins):
        import re
        self.selLIdindx = int(re.search(r'#(\d)\s', ins.text).group(1))
        # withoutHash = re.search(r'#\d\s(.+)', ins.text).group(1)
        Logger.debug(self.selLIdindx)

        proxysInx = dbRW.getProxysInx()
        self.selLId = proxysInx[self.selLIdindx][0]
        proxys = dbRW.getAllCurrentProxys(self.selLId)
        protocol = proxys[0][4]
        dbRW.updateConfig("proxysInx", self.selLId)
        scan_list = proxys

        self.scan_list = []
        if self.selLId:
            for l in scan_list:
                if not None in l:
                    self.scan_list.append({
                        "IP": l[0],
                        "SIZE": l[1],
                        "TIME": l[2],
                        "SPEED": l[3],
                        "top3c": l[6]
                    })

        unsort = self.scan_list
        if unsort:
            sort = sorted(unsort, key=lambda x: x['SPEED'], reverse=True)
            # print(sort)
            self.show_List()
            self.show_List(sort)

        self.configs['proxys'] = proxys
        self.configs['protocol'] = protocol

        self.root.ids.Slist.text = f"list : {ins.text}".upper()
        self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}"
        self.root.ids.Tproxys.text = f"proxys: {len(self.configs['proxys'])}"

        # print(getips)
        toast(ins.text)
        # print(indx)
        self.listSel.dismiss()
        insMain.caller.custom_color = get_color_from_hex(
            colors[self.theme_cls.primary_palette]["300"])
        if self.tap_target_list_view.state == 'open':
            self.tap_target_list_view.stop()

    def protPic(self):
        items = [{
            "text": protocol.upper(),
            "font_style": "Caption",
            "height": "36dp",
            "top_pad": "35dp",
            "bot_pad": "10dp"
        } for protocol in ['http', 'https', 'socks4', 'socks5']]
        self.protSel = MDDropdownMenu(
            caller=self.root.ids.Sprotocol,
            items=items,
            width_mult=3,
            opening_time=0.2,
            position='auto',
            selected_color=self.theme_cls.primary_dark_hue)
        self.protSel.bind(on_release=self.set_protocol,
                          on_dismiss=self.manuDismiss)

    def set_protocol(self, insMain, ins):
        self.configs['protocol'] = ins.text.lower()
        self.root.ids.Sprotocol.text = f"Protocol: {self.configs['protocol'].upper()}"

        toast(self.configs['protocol'])
        insMain.caller.custom_color = get_color_from_hex(
            colors[self.theme_cls.primary_palette]["300"])
        self.protSel.dismiss()

    def mirrorPic(self):

        mirrors = dbRW.getAllMirrors()

        self.configs['mirrors'] = mirrors
        items = [{
            "text": parse.urlparse(mirror[0]).netloc,
            "font_style": "Caption",
            "height": "36dp",
            "top_pad": "35dp",
            "bot_pad": "10dp"
        } for mirror in mirrors]
        self.mirrSel = MDDropdownMenu(
            caller=self.root.ids.Smirror,
            items=items,
            opening_time=0.2,
            width_mult=5,
            position='auto',
            max_height=0,
            selected_color=self.theme_cls.primary_dark_hue)
        self.mirrSel.bind(on_release=self.set_mirror,
                          on_dismiss=self.manuDismiss)

    def set_mirror(self, insMain, ins):
        miInx = 0
        for l in self.configs['mirrors']:
            if ins.text in l[0]:
                break
            miInx += 1

        self.configs['mirror'] = self.configs['mirrors'][miInx][0]
        self.root.ids.Smirror.text = f"Mirror: {ins.text}".upper()

        dbRW.updateConfig("proxysInx", self.selLId)
        dbRW.updateConfig("miInx", self.configs['miInx'])

        toast(self.configs['mirror'])
        insMain.caller.custom_color = get_color_from_hex(
            colors[self.theme_cls.primary_palette]["300"])
        self.mirrSel.dismiss()

    def update_screen(self, dt):
        try:
            while not self.pbar0.empty():
                sp = self.pbar0.get_nowait()
                if sp != 0:
                    self.root.ids.progressBar1.value += sp
                else:
                    self.root.ids.progressBar1.value = 0
        except Empty:
            pass

        try:
            while not self.pbar1.empty():
                sp = self.pbar1.get_nowait()
                if sp != 0:
                    self.root.ids.progressBar2.value += sp
                else:
                    self.root.ids.progressBar2.value = 0
        except Empty:
            pass

        try:
            while not self.pbar2.empty():
                sp = self.pbar2.get_nowait()
                if sp != 0:
                    self.root.ids.progressBar3.value += sp
                else:
                    self.root.ids.progressBar3.value = 0
        except Empty:
            pass

        try:
            proxysL = len(self.configs['proxys'])
            while not self.totalpb.empty():
                sp = self.totalpb.get_nowait()
                if sp != 0:
                    self.root.ids.totalpb.value += sp
                    comP = (self.root.ids.totalpb.value / proxysL) * 100
                    self.root.ids.totalpbText.text = f"{round(comP)}%"
                else:
                    self.root.ids.totalpb.max = proxysL
                    self.root.ids.totalpb.value = 0
        except Empty:
            pass

        self.speedcal()

        self.root.ids.Slist.text = f"list : #{self.selLIdindx} {agoConv(self.selLId)}".upper(
        )

    def start_scan(self, instance):
        # print("Clicked!!")
        if instance.text == "Start":
            self.mirrorPic()
            self.listPic()

            self.root.ids.Tproxys.text = f"proxys: {len(self.configs['proxys'])}"
            if len(self.configs['proxys']) == 0:
                try:
                    if self.configs['proxysInx']:
                        self.tap_target_list_view.start()
                        self.listSel.open()
                        # toast("Pick that list!")
                        return
                except:
                    pass
                PSTDialogInput().open()
                toast("First input proxys ip:port list then start scan.")
                return

            instance.text = "Stop"
            color = "#f44336"
            instance.md_bg_color = get_color_from_hex(color)
            self.theme_cls.primary_palette = "Red"
            if platform == "android": self._statusBarColor(color)
            self.scaning.put_nowait(1)
            self.running.put_nowait(1)

            IndexTime = datetime.now()
            dbRW.updateConfig('proxysInx', IndexTime)
            dbRW.updateProxysInx(IndexTime, self.selLId)
            dbRW.updateProxys(IndexTime, self.selLId)

            configs = dbRW.getAllConfigs()
            self.configs['totalScan'] = dbRW.getProxysInxTS(IndexTime)[0]
            self.root.ids.Tscan.text = f"scan: {self.configs['totalScan']}"
            # print(totalScan)

            self.configs['timeout'] = int(configs[0][3])
            self.configs['fileSize'] = int(configs[0][4])
            self.selLId = str(IndexTime)
            self.show_List()
            self.upScreen = Clock.schedule_interval(self.update_screen, 0.1)

            Thread(target=self.proxySpeedTest,
                   args=(
                       self.configs['proxys'],
                       self.configs['protocol'],
                       self.configs['mirror'],
                   )).start()

            # self.proxySpeedTest('start')
        elif instance.text == "Stoping":
            toast(f"Waiting for finish {self.root.ids.currentIP.text[8:]}!")
        else:
            while not self.scaning.empty():
                self.scaning.get_nowait()

            if not self.running.empty():
                instance.text = "Stoping"
                # instance.text_color
                color = "#9E9E9E"
                self.theme_cls.primary_palette = "Gray"
                instance.md_bg_color = get_color_from_hex(color)
                if platform == "android": self._statusBarColor(color)

    def downloadChunk(self, idx, proxy_ip, filename, mirror, protocol):
        Logger.info(f'Scaning {idx} : Started')
        try:
            proxies = {
                'http': f'{protocol}://{proxy_ip}',
                'https': f'{protocol}://{proxy_ip}'
            }
            req = get(mirror,
                      headers={
                          "Range":
                          "bytes=%s-%s" % (0, self.configs['fileSize']),
                          "user-agent": "Mozilla/5.0",
                      },
                      stream=True,
                      proxies=proxies,
                      timeout=self.configs['timeout'])
            with (open(f'{filename}{idx}', 'ab')) as f:
                start = datetime.now()
                chunkSize = 0
                # oldSpeed = 0
                chunkSizeUp = 1024
                for chunk in req.iter_content(chunk_size=chunkSizeUp):
                    end = datetime.now()
                    if 0.1 <= (end - start).seconds:
                        delta = round(
                            float((end - start).seconds) +
                            float(str('0.' + str((end - start).microseconds))),
                            3)
                        speed = round((chunkSize) / delta)
                        # if oldSpeed < speed:
                        # chunkSizeUp *= 3
                        # else:
                        #     chunkSizeUp = speed
                        oldSpeed = speed
                        start = datetime.now()
                        self.currentSpeed.put_nowait(speed)
                        chunkSize = 0
                    if chunk:
                        chunkSize += sys.getsizeof(chunk)
                        self.showupdate(idx)
                        f.write(chunk)
        except ProxyError:
            self.showupdate(idx, 'd')
            Logger.info(f"Thread {idx} : Could not connect to {proxy_ip}")
            return False
        except connError:
            self.showupdate(idx, 'd')
            Logger.info(f"Thread {idx} : Could not connect to {proxy_ip}")
            return False
        except IndexError:
            self.showupdate(idx, 'd')
            Logger.info(
                f'Thread {idx} : You must provide a testing IP:PORT proxy')
            return False
        except ConnectTimeout:
            self.showupdate(idx, 'd')
            Logger.info(f"Thread {idx} : ConnectTimeou for {proxy_ip}")
            return False
        except ReadTimeout:
            self.showupdate(idx, 'd')
            Logger.info(f"Thread {idx} : ReadTimeout for {proxy_ip}")
            return False
        except RuntimeError:
            self.showupdate(idx, 'd')
            Logger.info(
                f"Thread {idx} : Set changed size during iteration. {proxy_ip}"
            )
            return False
        except KeyboardInterrupt:
            self.showupdate(idx, 'd')
            Logger.info(f"Thread no {idx} : Exited by User.")

        self.showupdate(idx, 'd')

    def showupdate(self, idx, mode='u', error=True):
        if mode == 'u':
            if idx == 0:
                self.pbar0.put_nowait(1)
            elif idx == 1:
                self.pbar1.put_nowait(1)
            elif idx == 2:
                self.pbar2.put_nowait(1)
        elif mode == 'd':
            # color = "#f44336"
            if idx == 0:
                self.pbar0.put_nowait(0)
            elif idx == 1:
                self.pbar1.put_nowait(0)
            elif idx == 2:
                self.pbar2.put_nowait(0)

            self.root.ids.top_text.text = "0 KB/s"

    def proxySpeedTest(self, proxys, protocol, mirror):
        filename = 'chunk'
        unsort = list()
        sort = list()
        astTop3 = list()
        roundC = 0
        self.totalpb.put(0)
        Logger.debug(proxys)
        for c, part in enumerate(proxys):
            if self.scaning.empty(): break
            proxy_ip = part[0].strip()
            self.root.ids.currentIP.text = f"CURRENT: {proxy_ip}"
            # Removing before test chunk file
            for i in range(3):
                if exists(f'{filename}{i}'):
                    remove(f'{filename}{i}')

            # Starting chunk file downloading
            timeStart = datetime.now()
            downloaders = [
                Thread(
                    target=self.downloadChunk,
                    args=(idx, proxy_ip, filename, mirror, protocol),
                ) for idx in range(3)
            ]
            for _ in downloaders:
                _.start()
            for _ in downloaders:
                _.join()
            timeEnd = datetime.now()

            filesize = 0
            for i in range(3):
                try:
                    filesize = filesize + getsize(f'{filename}{i}')
                except FileNotFoundError:
                    continue

            filesizeM = round(filesize / pow(1024, 2), 2)
            delta = round(
                float((timeEnd - timeStart).seconds) +
                float(str('0.' + str((timeEnd - timeStart).microseconds))), 3)
            speed = round(filesize) / delta

            for i in range(3):
                if exists(f'{filename}{i}'):
                    remove(f'{filename}{i}')

            unsort.append({
                'IP': proxy_ip,
                'SIZE': filesizeM,
                'TIME': delta,
                'SPEED': int(speed),
                'top3c': part[6]
            })
            sort = self.sort_Type(unsort, showL=False)
            sortLL = len(sort)
            if sortLL >= 3:
                for t in range(sortLL):
                    if t < 3:
                        if sort[t]['SPEED'] != 0:
                            if not sort[t]['IP'] in astTop3:
                                sort[t]['top3c'] += 1
                                astTop3.append(sort[t]['IP'])
                    else:
                        for i in range(len(astTop3)):
                            if sort[t]['IP'] == astTop3[i]:
                                # print(i)
                                astTop3.pop(i)
                                sort[t]['top3c'] -= 1
                                break
            self.show_List(sort)
            self.save_UpdateDB(sort)
            self.totalpb.put(1)
            roundC = c
            # return True

        self.save_UpdateDB(sort)
        # print(roundC)
        # print(self.root.ids.totalpb.value)
        roundC += 1
        while True:
            if self.root.ids.totalpb.value == roundC:
                self.upScreen.cancel()
                break
        self.root.ids.start_stop.text = "Start"
        self.theme_cls.primary_palette = "LightBlue"
        self.root.ids.start_stop.md_bg_color = self.theme_cls.primary_color
        if platform == "android": self._statusBarColor()
        while not self.running.empty():
            self.running.get_nowait()
        Logger.info("Scan : Finished!")

    def sort_Change(self, inst, ckid):
        if ckid and inst.active:
            self.sort_Type(self.data_lists, mode=inst.text, reverse=False)
            inst.active = False
        elif ckid and inst.active == False:
            self.sort_Type(self.data_lists, mode=inst.text, reverse=True)
            inst.active = True

    def sort_Type(self, unsort, mode='SPEED', reverse=True, showL=True):
        if mode == 'SERVER': mode = 'IP'
        if mode == 'TOP3-%': mode = 'top3c'

        sort = sorted(unsort, key=lambda x: x[mode], reverse=reverse)
        if showL:
            self.show_List(sort)
        return sort

    def show_List(self, data=[]):
        # if not self.root.ids.backdrop_front_layer.data:
        # print(data)
        # print(len(self.root.ids.backdrop_front_layer.data))
        totalP = len(self.configs['proxys'])
        ddict = {
            "viewclass": "ProxyShowList",
            "text": "",
            "text1": "",
            "text2": "",
            "text3": "",
            "text4": "",
            "on_release": lambda: toast("empty!")
        }
        if not data:
            self.root.ids.backdrop_front_layer.data = []
            for i in range(totalP):
                self.root.ids.backdrop_front_layer.data.append(ddict)
        else:
            for i in range(totalP):
                try:
                    _ = data[i]
                    self.root.ids.backdrop_front_layer.data[i] = {
                        "viewclass": "ProxyShowList",
                        "text": data[i]['IP'],
                        "text1":
                        f"{round((data[i]['top3c']/self.configs['totalScan'])*100)} %",
                        "text2": f"{data[i]['SIZE']} MB",
                        "text3": sec_to_mins(float(data[i]['TIME'])),
                        "text4":
                        f"{size(data[i]['SPEED'], system=alternative)}/s",
                        "on_release":
                        lambda x=data[i]['IP']: self.copy_proxyip(x),
                    }
                except IndexError:
                    self.root.ids.backdrop_front_layer.data[i] = ddict

            self.data_lists = data

    def copy_proxyip(self, data):
        toast(f"Copied: {data}")
        Clipboard.copy(data)

    def speedcal(self):
        speed = 0
        try:
            while not self.currentSpeed.empty():
                speed += self.currentSpeed.get_nowait()
        except Empty:
            pass

        if speed != 0:
            self.root.ids.top_text.text = f"{size(speed, system=alternative)}/s"
Exemplo n.º 19
0
class AmazonApp(MDApp):
    def build(self):
        screen = Screen()
        self.theme_cls.theme_style = "Light"
        self.helper_string = Builder.load_string(code_helper)
        screen.add_widget(self.helper_string)
        self.skip_target_view = MDTapTargetView(
            widget=self.helper_string.get_screen(
                'firstwelcome').ids.welcome_skip,
            title_text="Next",
            widget_position="left_bottom",
            title_text_size="20sp",
            description_text="GO next",
            outer_radius='80dp',
            description_text_color=[1, 0, 0, 0],
            outer_circle_alpha=0.40,
            target_radius='40dp')
        self.android_target_view = MDTapTargetView(
            widget=self.helper_string.get_screen(
                'androidinfo').ids.android_info,
            title_text="Hey!!",
            widget_position="center",
            title_text_size="20sp",
            title_position="right_top",
            description_text="I am your assistant\nClick on me",
            outer_radius='180dp',
            description_text_color=[0, 0, 0, 1],
            outer_circle_alpha=0.5,
            target_radius='50dp')
        self.skip_target_view.start()
        self.android_target_view.start()

        #self.dob initialize
        self.dob_entered = True
        return screen

    def theme_switcher(self):
        if self.theme_cls.theme_style == "Dark":
            self.theme_cls.theme_style = "Light"
        else:
            self.theme_cls.theme_style = "Dark"

    def tap_target_stop(self):
        self.skip_target_view.stop()

    def android_info_targerview_stop(self):
        self.android_target_view.stop()

    def help_chip(self, instance, value):
        help_cancel_btn_first = MDIconButton(
            icon='checkbox-marked-circle-outline',
            on_release=self.help_close_dialog_btn)
        self.help_dialog = MDDialog(
            title='Help',
            text=
            'Little android is your assistant\nClick the android for more Info',
            size_hint=(0.7, 0.1),
            buttons=[help_cancel_btn_first])
        self.help_dialog.open()

    def help_close_dialog_btn(self, obj):
        self.help_dialog.dismiss()

    def username_checker(self):
        username_check_false = True
        self.username_text_data = self.helper_string.get_screen(
            'usernamescreen').ids.username_text.text
        # print(self.username_text_data)
        try:
            int(self.username_text_data)
        except:

            username_check_false = False
        if username_check_false or self.username_text_data.split() == []:
            cancel_btn_username_dialogue = MDFlatButton(
                text='Retry', on_release=self.close_username_dialog)
            self.username_dialoge = MDDialog(
                title='Invalid Username',
                text='Please Enter a valid Username',
                size_hint=(0.7, 0.2),
                buttons=[cancel_btn_username_dialogue])
            self.username_dialoge.open()
        else:
            screen_usernamescreen = self.helper_string.get_screen(
                'usernamescreen')
            screen_usernamescreen.ids.username_enter.disabled = False
            screen_usernamescreen.ids.username_check_extra_button.icon = 'account-check-outline'
            screen_usernamescreen.ids.username_check_btn.text_color = [
                1, 1, 1, 0
            ]
            screen_usernamescreen.ids.username_check_btn.md_bg_color = [
                1, 1, 1, 0
            ]
            screen_usernamescreen.ids.username_check_extra_button.text_color = self.theme_cls.primary_color
            screen_usernamescreen.ids.username_check_extra_button.pos_hint = {
                'center_x': 0.5,
                'center_y': 0.62
            }
            screen_usernamescreen.ids.username_check_extra_button.user_font_size = '60sp'

    def close_username_dialog(self, obj):
        self.username_dialoge.dismiss()


# DOB Picker
#self.dob for Date of birth

    def show_date_picker(self):
        date_dialog = MDDatePicker(
            callback=self.get_date,
            year=1999,
            month=1,
            day=1,
        )
        date_dialog.open()

    def get_date(self, date):
        self.dob = date
        dob_input_screen_selector = self.helper_string.get_screen('dobinput')
        #here i put the next button disbaled as False so user can enter in that window
        dob_input_screen_selector.ids.dob_enter.disabled = False
        dob_input_screen_selector.ids.account_shield.icon = 'shield-account'
        dob_input_screen_selector.ids.dob.text = str(self.dob)
        dob_input_screen_selector.ids.secure.text_color = [0, 1, 0, 0.7]
        self.store.put('userInfo',
                       name=self.username_text_data,
                       dob=str(self.dob))
        self.username_changer()

    def navigation_draw(self):
        self.helper_string.get_screen('about').manager.current = "about"

    def username_changer(self):
        self.helper_string.get_screen('main').ids.title.title = self.store.get(
            'userInfo')['name']

    def price(self):
        link = self.helper_string.get_screen('main').ids.Link.text
        if link.split() != []:
            self.price_finder(URL=link)
        else:

            self.helper_string.get_screen('main').manager.current = "main"

    def price_finder(self, URL):
        try:
            r = requests.get(URL, headers={"User-Agent": "Defined"})
            soup = BeautifulSoup(r.content, "html.parser")
            try:
                if 'amazon' in URL:
                    try:
                        price_one = soup.find(id="priceblock_dealprice")
                        price = price_one
                    except:
                        print("in ourprice")
                        price_two = soup.find(id="priceblock_ourprice")
                        price = price_two
                elif 'flipkart' in URL:
                    try:
                        price = soup.find(class_='_1vC4OE _3qQ9m1')
                    except:
                        self.helper_string.get_screen(
                            'main').manager.current = "main"
            except:
                self.helper_string.get_screen('main').manager.current = "main"

            if price == None:
                self.helper_string.get_screen('main').manager.current = "main"
            else:
                current_price = price.get_text()
                self.helper_string.get_screen(
                    'result').ids.realPrice.text = current_price

        except:
            self.helper_string.get_screen('main').manager.current = "main"

    def setting_username_checker(self):
        username_check_false = True
        self.new_username = self.helper_string.get_screen(
            'setting').ids.new_username.text
        try:
            int(self.new_username)
        except:

            username_check_false = False
        if username_check_false or self.new_username.split() == []:
            cancel_btn_username_dialogue = MDFlatButton(
                text='Retry', on_release=self.close_username_dialog)
            self.username_dialoge = MDDialog(
                title='Invalid Username',
                text='Please Enter a valid Username',
                size_hint=(0.7, 0.2),
                buttons=[cancel_btn_username_dialogue])
            self.username_dialoge.open()
        else:
            self.username_text_data = self.new_username
            self.store.put('userInfo', name=self.username_text_data)
            self.username_changer()
            self.helper_string.get_screen('main').manager.current = "main"

    def change_edit_username(self):
        self.helper_string.get_screen(
            'setting').ids.new_username.text = self.store.get(
                'userInfo')['name']

    def on_start(self):
        self.store = JsonStore("userProfile.json")
        try:
            if self.store.get('userInfo')['name'] != "":
                self.username_changer()
                self.helper_string.get_screen('main').manager.current = "main"
        except KeyError:
            self.helper_string.get_screen(
                'firstwelcome').manager.current = 'firstwelcome'
Exemplo n.º 20
0
 def song_details(self, i):
     self.s_manager = self.root.ids.screen_manager
     self.change_screen('SongDetailsScreen')
     self.details_screen = self.root.ids.SongDetailsScreen
     self.details_screen.clear_widgets()
     self.song_name = self.search_data[i]['title'].replace(
         "&quot;", "'").replace("&amp;", "&").replace("&#039;", "'")
     self.song_id = self.search_data[i]['id']
     try:
         self.artist_name = self.search_data[i]['more_info'][
             'primary_artists'].replace("&quot;", "'").replace(
                 "&amp;", "&").replace("&#039;", "'")
         self.album = self.search_data[i]['album'].replace(
             "&quot;", "'").replace("&amp;", "&").replace("&#039;", "'")
     except:
         self.artist_name = self.search_data[i]['subtitle']
     self.image_url = self.search_data[i]['image'].replace(
         '50x50', '500x500').replace('150x150', '500x500')
     self.image_path = os.path.join(self.data_path, self.song_id + '.jpg')
     self.fetch_thread = threading.Thread(target=self.fetch_details)
     self.fetch_thread.start()
     self.details_screen.add_widget(
         MDIconButton(icon='chevron-left',
                      pos_hint={
                          "center_x": 0.05,
                          "center_y": 0.95
                      },
                      on_press=lambda x: self.back_screen()))
     song_image = AsyncImage(source=self.image_url,
                             pos_hint={
                                 "center_x": 0.5,
                                 "center_y": 0.5
                             },
                             allow_stretch=True)
     card = MDCard(orientation='vertical',
                   pos_hint={
                       "center_x": 0.5,
                       "center_y": 0.65
                   },
                   size_hint=(None, None),
                   size=(self.win_size * 0.9, self.win_size * 0.9))
     card.add_widget(song_image)
     self.details_screen.add_widget(card)
     self.details_screen.add_widget(
         MDLabel(text=self.song_name,
                 halign='center',
                 theme_text_color='Custom',
                 text_color=self.theme_cls.primary_color,
                 font_style='H4',
                 bold=True,
                 pos_hint={"top": 0.84}))
     self.details_screen.add_widget(
         MDLabel(text=self.artist_name,
                 halign='center',
                 theme_text_color='Secondary',
                 font_style='H6',
                 pos_hint={"top": 0.8}))
     self.spinner = MDSpinner(size_hint=(None, None),
                              size=("50", "50"),
                              pos_hint={
                                  'center_x': 0.5,
                                  "center_y": 0.15
                              },
                              active=True)
     #self.details_screen.add_widget(MDLabel(text=self.album, halign='center', theme_text_color='Hint', font_style='H6', pos_hint={"top":0.9}))
     self.heart_icon = MDIconButton(icon='heart-outline',
                                    user_font_size="30sp",
                                    theme_text_color='Secondary',
                                    pos_hint={
                                        "center_x": 0.1,
                                        "center_y": 0.15
                                    },
                                    on_press=lambda x: self.add_fav())
     self.details_screen.add_widget(self.heart_icon)
     self.play_progress = MDProgressBar(pos_hint={
         'center_x': 0.5,
         'center_y': 0.25
     },
                                        size_hint_x=0.9,
                                        value=0,
                                        color=self.theme_cls.primary_color)
     self.details_screen.add_widget(self.play_progress)
     self.tap_target_view = MDTapTargetView(
         widget=self.heart_icon,
         title_text="Add to Favorites",
         description_text="Feature currently under development",
         widget_position="left_bottom",
     )
     self.details_screen.add_widget(
         MDIconButton(icon="chevron-double-left",
                      pos_hint={
                          "center_x": .3,
                          "center_y": .15
                      },
                      user_font_size="50sp",
                      on_release=lambda x: self.rewind()))
     self.details_screen.add_widget(
         MDIconButton(icon="chevron-double-right",
                      pos_hint={
                          "center_x": .7,
                          "center_y": .15
                      },
                      user_font_size="50sp",
                      on_release=lambda x: self.forward()))
     self.play_btn = MDFloatingActionButton(
         icon='play',
         pos_hint={
             'center_x': 0.5,
             "center_y": 0.15
         },
         user_font_size="50sp",
         md_bg_color=(1, 1, 1, 1),
         elevation_normal=10,
         on_press=lambda x: self.play_song_online())
     self.details_screen.add_widget(self.play_btn)
     self.details_screen.add_widget(
         MDIconButton(icon='arrow-collapse-down',
                      user_font_size="30sp",
                      theme_text_color='Secondary',
                      pos_hint={
                          'center_x': 0.9,
                          "center_y": 0.15
                      },
                      on_press=lambda x: self.download_bar()))
     try:
         self.dia.dismiss()
     except:
         pass
Exemplo n.º 21
0
class MyApp(MDApp):
    title = "Black Hole"
    __version__ = "0.7"
    status = True
    play_status = 'stop'
    last_screen = []
    win_size = min(Window.size)

    #    def on_start(self):
    #        self.root.ids.tabs.add_widget(Tab(text='Local'))
    #        self.root.ids.tabs.add_widget(Tab(text='Global'))
    #def on_start(self):
    #    self.trend_list = self.root.ids.trend_list
    #    self.trend_list.clear_widgets()
    #    add_trend_thread=threading.Thread(target=self.add_songs)
    #    add_trend_thread.start()

    def build(self):
        if self.user_data.exists('theme'):
            self.theme_cls.theme_style = self.user_data.get('theme')['mode']
        else:
            self.user_data.put('theme', mode='Light')
        if self.user_data.exists('accent'):
            self.theme_cls.primary_palette = self.user_data.get(
                'accent')['color']
        if self.theme_cls.theme_style == "Dark":
            self.root.ids.dark_mode_switch.active = True
        #self.theme_cls.primary_hue = "A400"
        self.theme_cls.accent_palette = self.theme_cls.primary_palette
        Loader.loading_image = 'cover.jpg'
        #return Builder.load_string(main)
        # if self.user_data.exists('sync'):
        #     if int(time.time()) - int(self.user_data.get('sync')['time']) > 21600:
        #         sync_thread = threading.Thread(target=self.get_chart)
        #         sync_thread.start()
        #         self.user_data.put('sync', time=time.time())
        #     else:
        #         print('already synced')
        # else:
        #     sync_thread = threading.Thread(target=self.get_chart)
        #     sync_thread.start()

    def notify(self,
               title='',
               message='',
               app_name='',
               app_icon='',
               timeout=10,
               ticker='',
               toast=False):
        AndroidString = autoclass('java.lang.String')
        PythonActivity = autoclass('org.kivy.android.PythonActivity')
        NotificationBuilder = autoclass('android.app.Notification$Builder')
        Context = autoclass('android.content.Context')
        Drawable = autoclass('org.test.notify.R$drawable')
        app_icon = Drawable.icon
        notification_builder = NotificationBuilder(PythonActivity.mActivity)
        notification_builder.setContentTitle(
            AndroidString(title.encode('utf-8')))
        notification_builder.setContentText(
            AndroidString(message.encode('utf-8')))
        notification_builder.setSmallIcon(app_icon)
        notification_builder.setAutoCancel(True)
        notification_service = notification_service = PythonActivity.mActivity.getSystemService(
            Context.NOTIFICATION_SERVICE)
        notification_service.notify(0, notification_builder.build())

    def tap_target_start(self):
        if self.tap_target_view.state == "close":
            self.tap_target_view.start()
        else:
            self.tap_target_view.stop()

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.user_data_path = os.path.join(self.user_data_dir, 'data.json')
        self.user_data = JsonStore(self.user_data_path)
        Window.bind(on_keyboard=self.events)
        if self.user_data.exists('download_path'):
            self.path = self.user_data.get('download_path')['path']
        else:
            self.path = os.path.join(os.getenv('EXTERNAL_STORAGE'), 'Songs')
        self.data_path = os.path.join(self.user_data_dir, 'cache')
        #self.user_data.put('accent', color='Blue')
        self.manager_open = False
        self.file_manager = MDFileManager(
            exit_manager=self.exit_manager,
            select_path=self.select_path,
        )
        self.file_manager.ext = [".m4a", ".mp3"]
        if os.path.exists(self.path):
            pass
        else:
            os.mkdir(self.path)
        if os.path.exists(self.data_path):
            pass
        else:
            os.mkdir(self.data_path)
        if not os.path.exists(self.user_data_path):
            self.user_data.put('theme', mode='Light')
            self.user_data.put('accent', color='Blue')

    def change_theme(self):
        if self.root.ids.dark_mode_switch.active == True:
            self.theme_cls.theme_style = "Dark"
            self.user_data.put('theme', mode='Dark')
        else:
            self.theme_cls.theme_style = "Light"
            self.user_data.put('theme', mode='Light')

    def on_tab_switch(self, instance_tabs, instance_tab, instance_tab_label,
                      tab_text):
        instance_tab.ids.label.text = tab_text

    def check_update(self):
        webbrowser.open_new(
            'https://github.com/Sangwan5688/Black_Hole-music_downloader')

    def get_chart(self):
        with open('top_local_chart.csv', 'wb') as f:
            f.write(
                requests.get(
                    'https://spotifycharts.com/regional/in/daily/latest/download'
                ).content)


#        with open('top_global_chart.csv', 'wb') as f:
#            f.write(requests.get("https://spotifycharts.com/regional/global/daily/latest/download").content)
        self.user_data.put('sync', time=time.time())

    def add_top(self):
        self.top_list = self.root.ids.top_list
        #        self.top_global_list = self.root.ids.top_global_list
        if self.top_list.children == []:
            Clock.schedule_once(self.thread_top)
            self.dia = MDDialog(text="Loading spotify top 200 chart",
                                size_hint=(0.7, 1))
            self.dia.open()

    def thread_top(self, *args):
        self.add_top_thread = threading.Thread(target=self.add_songs)
        self.add_top_thread.start()

    def add_trend(self):
        Clock.schedule_once(self.add_trend2)
        self.dia = MDDialog(text="Loading trending songs", size_hint=(0.7, 1))
        self.dia.open()

    def add_trend2(self, *args):
        if self.root.ids.trend_grid.children == []:
            for key, values in playlist_ids.items():
                self.get_playlist(key, values)
        self.dia.dismiss()
        #for i in ["znKA,YavndBuOxiEGmm6lQ__", "8MT-LQlP35c_", "LdbVc1Z5i9E_", "xXiMISqMjsrfemJ68FuXsA__"]:
        #    executor.submit(self.get_playlist, i)
        #executor.shutdown()

    def add_songs(self):
        url = 'https://spotifycharts.com/regional/in/daily/latest/download'
        with closing(requests.get(url, stream=True)) as r:
            f = (line.decode('utf-8') for line in r.iter_lines())
            reader = csv.reader(f, delimiter=',', quotechar='"')
            for row in reader:
                try:
                    pos = int(row[0])
                    song_name = row[1]
                    art_name = row[2]
                    lst = TwoLineAvatarListItem(
                        text="{}. {}".format(pos, song_name),
                        secondary_text=art_name,
                        on_press=lambda x, y=song_name: self.select_spotify(y))
                    lst.add_widget(IconLeftWidget(icon='music-note-outline'))
                    self.top_list.add_widget(lst)
                except:
                    continue
        try:
            self.dia.dismiss()
        except:
            pass

    def select_spotify(self, song_name):
        self.dia = MDDialog(text="Loading..", size_hint=(0.7, 1))
        self.dia.open()
        spoti = threading.Thread(target=self.spoti_thread, args=(song_name, ))
        spoti.start()

    def spoti_thread(self, song_name):
        response = requests.get(search_base_url + song_name)
        result = response.content.decode()
        self.search_data = json.loads(
            result.replace("&quot;",
                           "'").replace("&amp;",
                                        "&").replace("&#039;",
                                                     "'"))['songs']['data']
        self.song_details(0)

    def push_notify(self, head):
        notification.notify(head, "Download complete")

    def download_list(self):
        self.down_list = self.root.ids.downloadlist
        self.down_list.clear_widgets()
        td = threading.Thread(target=self.add_songs_downlist)
        td.start()

    def add_songs_downlist(self):
        self.down_path_list = []
        for root, dirs, files in os.walk(os.getenv('EXTERNAL_STORAGE')):
            for filename in files:
                if os.path.splitext(filename)[1] in [
                        ".mp3", ".m4a", ".ogg", ".wav"
                ]:
                    self.down_path_list.append(
                        (os.path.join(root, filename), filename))
        for i in range(len(self.down_path_list)):
            lst = OneLineAvatarListItem(
                text=self.down_path_list[i][1],
                on_press=lambda x, y=i: self.play_song(y))
            lst.add_widget(IconLeftWidget(icon='music-note-outline'))
            self.down_list.add_widget(lst)

    def show_data(self, query):
        close_btn = MDFlatButton(text="Close", on_release=self.close_dialog)
        if query == '':
            self.dia = MDDialog(title="Invalid Name",
                                text="Please enter a song name",
                                size_hint=(0.7, 1),
                                buttons=[close_btn])
            self.dia.open()

        else:
            self.change_screen('SongListScreen')
            self.dia = MDDialog(text="Searching for songs ...",
                                size_hint=(0.7, 1))
            self.list_view = self.root.ids.container
            self.list_view.clear_widgets()
            self.dia.open()
            req = UrlRequest(search_base_url + query.replace(' ', '+'),
                             self.show_list)

    def show_list(self, req, result):
        self.search_data = json.loads(
            result.replace("&quot;",
                           "'").replace("&amp;",
                                        "&").replace("&#039;",
                                                     "'"))['songs']['data']
        for i in range(len(self.search_data)):
            lst = TwoLineAvatarListItem(
                text=self.search_data[i]['title'].replace(
                    "&quot;", "'").replace("&amp;",
                                           "&").replace("&#039;", "'"),
                secondary_text=self.search_data[i]['more_info']
                ['primary_artists'].replace("&quot;", "'").replace(
                    "&amp;", "&").replace("&#039;", "'"),
                on_press=lambda x, y=i: self.song_details(y))
            lst.add_widget(IconLeftWidget(icon='music-note-outline'))
            self.list_view.add_widget(lst)
        self.dia.dismiss()

    def fetch_details(self):
        print('started fetching details')
        self.song_data = json.loads(
            requests.get(song_details_base_url + self.song_id).text.replace(
                "&quot;", "'").replace("&amp;",
                                       "&").replace("&#039;",
                                                    "'"))[self.song_id]
        try:
            url = self.song_data['media_preview_url']
            url = url.replace("preview", "aac")
            if self.song_data['320kbps'] == "true":
                url = url.replace("_96_p.mp4", "_320.mp4")
            else:
                url = url.replace("_96_p.mp4", "_160.mp4")
            self.song_dwn_url = url
        except KeyError or TypeError:
            self.song_data['media_url'] = self.decrypt_url(
                self.song_data['encrypted_media_url'])
            if self.song_data['320kbps'] != "true":
                self.song_dwn_url = self.song_data['media_url'].replace(
                    "_320.mp4", "_160.mp4")

        self.song_name = self.song_data['song']
        self.album = self.song_data['album']
        self.artist_name = self.song_data["primary_artists"]
        self.featured_artist = self.song_data["featured_artists"]
        self.year = self.song_data["year"]
        self.genre = (self.song_data["language"]).capitalize()
        self.prepare(self.song_dwn_url)
        self.root.ids.SongDetailsScreen.add_widget(
            MDLabel(text=self.convert_sec(self.sound.getDuration()),
                    halign='right',
                    theme_text_color='Secondary',
                    padding_x='20dp',
                    pos_hint={"top": 0.725}))
        self.play_stamp = (MDLabel(text=self.convert_sec(
            self.sound.getCurrentPosition()),
                                   halign='left',
                                   theme_text_color='Secondary',
                                   padding_x='20dp',
                                   pos_hint={"top": 0.725}))
        self.root.ids.SongDetailsScreen.add_widget(self.play_stamp)
        print('finished fetching details')

    def get_playlist(self, title, listId):
        image = AsyncImage(source=playlist_images[listId],
                           size_hint=(1, 1),
                           pos_hint={'top': 0.9},
                           allow_stretch=True)
        card = MDCard(orientation='vertical',
                      border_radius=15,
                      radius=[0, 0, 15, 15],
                      pos_hint={
                          "center_x": 0.5,
                          "center_y": 0.5
                      },
                      size_hint=(None, None),
                      size=(self.win_size * 0.3, self.win_size * 0.3))
        card.add_widget(image)
        self.root.ids.trend_grid.add_widget(
            MDTextButton(text=title,
                         pos_hint={'center_x': 0.5},
                         on_press=lambda x: self.show_top(title, listId)))
        self.root.ids.trend_grid.add_widget(card)
        self.root.ids.trend_grid.add_widget(MDLabel(text=''))
        self.root.ids.trend_grid.add_widget(MDLabel(text=''))
        self.root.ids.trend_grid.add_widget(MDLabel(text=''))
        self.root.ids.trend_grid.add_widget(MDLabel(text=''))

    def show_top(self, ttl, Id):
        self.dia = MDDialog(text="Loading {}".format(ttl), size_hint=(0.7, 1))
        self.dia.open()
        t3 = threading.Thread(target=self.show_top2, args=(ttl, Id))
        t3.start()

    def show_top2(self, ttl, Id):
        self.tlist = self.root.ids.trend_list
        self.root.ids.trend_toolbar.title = ttl
        self.tlist.clear_widgets()
        try:
            response = requests.get(playlist_details_base_url.format(Id))
            if response.status_code == 200:
                songs_json = response.text.encode().decode()
                songs_json = json.loads(songs_json)
                self.search_data = songs_json['list']
                for i in range(int(len(songs_json['list']))):
                    #print(items['id'])
                    #print(i)
                    #print(songs_json['list'][i]['title'])
                    lst = TwoLineAvatarListItem(
                        text=songs_json['list'][i]['title'].replace(
                            "&quot;", "'").replace("&amp;",
                                                   "&").replace("&#039;", "'"),
                        secondary_text=songs_json['list'][i]
                        ['subtitle'].replace("&quot;", "'").replace(
                            "&amp;", "&").replace("&#039;", "'"),
                        on_press=lambda x, y=i: self.song_details(y))
                    lst.add_widget(IconLeftWidget(icon='music-note-outline'))
                    self.tlist.add_widget(lst)
            self.change_screen('TrendListScreen')
        except Exception as e:
            print(e)
        self.dia.dismiss()

    def decrypt_url(url):
        des_cipher = des(b"38346591",
                         ECB,
                         b"\0\0\0\0\0\0\0\0",
                         pad=None,
                         padmode=PAD_PKCS5)
        enc_url = base64.b64decode(url.strip())
        dec_url = des_cipher.decrypt(enc_url,
                                     padmode=PAD_PKCS5).decode('utf-8')
        dec_url = dec_url.replace("_96.mp4", "_320.mp4")
        return dec_url

    def song_details(self, i):
        self.s_manager = self.root.ids.screen_manager
        self.change_screen('SongDetailsScreen')
        self.details_screen = self.root.ids.SongDetailsScreen
        self.details_screen.clear_widgets()
        self.song_name = self.search_data[i]['title'].replace(
            "&quot;", "'").replace("&amp;", "&").replace("&#039;", "'")
        self.song_id = self.search_data[i]['id']
        try:
            self.artist_name = self.search_data[i]['more_info'][
                'primary_artists'].replace("&quot;", "'").replace(
                    "&amp;", "&").replace("&#039;", "'")
            self.album = self.search_data[i]['album'].replace(
                "&quot;", "'").replace("&amp;", "&").replace("&#039;", "'")
        except:
            self.artist_name = self.search_data[i]['subtitle']
        self.image_url = self.search_data[i]['image'].replace(
            '50x50', '500x500').replace('150x150', '500x500')
        self.image_path = os.path.join(self.data_path, self.song_id + '.jpg')
        self.fetch_thread = threading.Thread(target=self.fetch_details)
        self.fetch_thread.start()
        self.details_screen.add_widget(
            MDIconButton(icon='chevron-left',
                         pos_hint={
                             "center_x": 0.05,
                             "center_y": 0.95
                         },
                         on_press=lambda x: self.back_screen()))
        song_image = AsyncImage(source=self.image_url,
                                pos_hint={
                                    "center_x": 0.5,
                                    "center_y": 0.5
                                },
                                allow_stretch=True)
        card = MDCard(orientation='vertical',
                      pos_hint={
                          "center_x": 0.5,
                          "center_y": 0.65
                      },
                      size_hint=(None, None),
                      size=(self.win_size * 0.9, self.win_size * 0.9))
        card.add_widget(song_image)
        self.details_screen.add_widget(card)
        self.details_screen.add_widget(
            MDLabel(text=self.song_name,
                    halign='center',
                    theme_text_color='Custom',
                    text_color=self.theme_cls.primary_color,
                    font_style='H4',
                    bold=True,
                    pos_hint={"top": 0.84}))
        self.details_screen.add_widget(
            MDLabel(text=self.artist_name,
                    halign='center',
                    theme_text_color='Secondary',
                    font_style='H6',
                    pos_hint={"top": 0.8}))
        self.spinner = MDSpinner(size_hint=(None, None),
                                 size=("50", "50"),
                                 pos_hint={
                                     'center_x': 0.5,
                                     "center_y": 0.15
                                 },
                                 active=True)
        #self.details_screen.add_widget(MDLabel(text=self.album, halign='center', theme_text_color='Hint', font_style='H6', pos_hint={"top":0.9}))
        self.heart_icon = MDIconButton(icon='heart-outline',
                                       user_font_size="30sp",
                                       theme_text_color='Secondary',
                                       pos_hint={
                                           "center_x": 0.1,
                                           "center_y": 0.15
                                       },
                                       on_press=lambda x: self.add_fav())
        self.details_screen.add_widget(self.heart_icon)
        self.play_progress = MDProgressBar(pos_hint={
            'center_x': 0.5,
            'center_y': 0.25
        },
                                           size_hint_x=0.9,
                                           value=0,
                                           color=self.theme_cls.primary_color)
        self.details_screen.add_widget(self.play_progress)
        self.tap_target_view = MDTapTargetView(
            widget=self.heart_icon,
            title_text="Add to Favorites",
            description_text="Feature currently under development",
            widget_position="left_bottom",
        )
        self.details_screen.add_widget(
            MDIconButton(icon="chevron-double-left",
                         pos_hint={
                             "center_x": .3,
                             "center_y": .15
                         },
                         user_font_size="50sp",
                         on_release=lambda x: self.rewind()))
        self.details_screen.add_widget(
            MDIconButton(icon="chevron-double-right",
                         pos_hint={
                             "center_x": .7,
                             "center_y": .15
                         },
                         user_font_size="50sp",
                         on_release=lambda x: self.forward()))
        self.play_btn = MDFloatingActionButton(
            icon='play',
            pos_hint={
                'center_x': 0.5,
                "center_y": 0.15
            },
            user_font_size="50sp",
            md_bg_color=(1, 1, 1, 1),
            elevation_normal=10,
            on_press=lambda x: self.play_song_online())
        self.details_screen.add_widget(self.play_btn)
        self.details_screen.add_widget(
            MDIconButton(icon='arrow-collapse-down',
                         user_font_size="30sp",
                         theme_text_color='Secondary',
                         pos_hint={
                             'center_x': 0.9,
                             "center_y": 0.15
                         },
                         on_press=lambda x: self.download_bar()))
        try:
            self.dia.dismiss()
        except:
            pass

    def add_fav(self):
        if self.heart_icon.icon == 'heart-outline':
            self.heart_icon.icon = 'heart'
            self.heart_icon.theme_text_color = "Custom"
            self.heart_icon.text_color = (1, 0, 0, 1)
            self.tap_target_view.start()
            #toast("Feature under development")

        elif self.heart_icon.icon == 'heart':
            #self.heart_icon.icon = 'heart-broken'
            self.heart_icon.icon = 'heart-outline'
            self.heart_icon.theme_text_color = 'Secondary'
            #self.heart_icon.text_color = self.theme_cls.text_color
            toast("Removed from Favorites")

    def change_screen(self, screen, *args):
        if self.root.ids.screen_manager.current == 'SongDetailsScreen' or self.root.ids.screen_manager.current == 'PlayScreen':
            try:
                self.stop()
            except:
                pass
        if args:
            self.root.ids.screen_manager.transition.direction = args[0]
            if args[0] != 'right':
                self.last_screen.append(self.root.ids.screen_manager.current)

        else:
            self.root.ids.screen_manager.transition.direction = 'left'
            self.last_screen.append(self.root.ids.screen_manager.current)
        self.root.ids.screen_manager.current = screen

    def back_screen(self):
        if self.root.ids.screen_manager.current != 'MainScreen':
            self.change_screen(self.last_screen[-1], 'right')
            self.last_screen.pop(-1)

    def cancel(self):
        self.download_progress.color = 1, 0, 0, 1
        self.status = False
        t3 = threading.Thread(target=self.cancel2)
        t3.start()

    def cancel2(self):
        time.sleep(0.5)
        try:
            os.remove("{}/{} - {}.m4a".format(self.data_path, self.song_name,
                                              self.artist_name))
            print('removed')
        except:
            print('failed to remove')
            pass
        self.dia.dismiss()
        self.status = True

    def download_bar(self):
        self.download_progress = MDProgressBar(
            pos_hint={
                'center_x': 0.5,
                'center_y': 0.5
            },
            size_hint_x=0.8,
            value=0,
            color=self.theme_cls.primary_color)
        self.dia = MDDialog(text='Downloading',
                            buttons=[
                                MDFlatButton(
                                    text="CANCEL",
                                    text_color=self.theme_cls.primary_color,
                                    on_press=lambda x: self.cancel())
                            ])
        #self.dia.add_widget(IconLeftWidget(icon='download', pos_hint={'center_x': .1, 'center_y': .1}))
        self.dia.add_widget(self.download_progress)
        self.dia.open()
        t2 = threading.Thread(target=self.download_song)
        t2.start()

    def play_song_online(self):
        self.fetch_thread.join()
        if self.sound:
            #print("Sound found at %s" % self.sound.source)
            #print("Sound is %.3f seconds" % self.sound.length)
            if self.play_status == 'pause' or self.play_status == 'stop':
                self.play_btn.icon = 'pause'
                self.play()
                lnth = self.sound.getDuration()
                t2 = threading.Thread(target=self.online_play_bar,
                                      args=(lnth, ))
                t2.start()
            elif self.play_status == 'play':
                self.play_btn.icon = 'play'
                self.pause()
        else:
            time.sleep(0.5)
            self.play_song_online

    def online_play_bar(self, length, *args):
        while True:
            if length != 0:
                self.play_progress.value = 100 * (
                    self.sound.getCurrentPosition()) / length
            #print(self.progress.value)
            time.sleep(1)
            self.play_stamp.text = self.convert_sec(
                self.sound.getCurrentPosition())
            if self.play_status == 'stop':
                break
            if self.play_stamp.text == self.length_stamp.text:
                self.play_song(args[0] + 1)

    def play_song(self, i):
        try:
            self.stop()
        except:
            pass
        link = self.down_path_list[i][0]
        if self.root.ids.screen_manager.current != 'PlayScreen':
            self.change_screen("PlayScreen")
        self.prepare(link)
        if link.endswith('.m4a'):
            self.audio = MP4(link)
            self.play_song_name = self.audio.get('\xa9nam', ['Unknown'])[0]
            #print(audio['\xa9alb'])
            self.play_art_name = self.audio.get('\xa9ART', ['Unknown'])[0]
            #print(audio['\xa9day'])
            #print(audio['\xa9gen'])
            try:
                self.img_data = self.audio["covr"][0]
            except:
                with open('cover.jpg', 'rb') as f:
                    self.img_data = f.read()
        elif link.endswith('.mp3'):
            self.audio = MP3(link, ID3=EasyID3)
            self.audio_tags = ID3(link)
            self.play_song_name = self.audio.get('title', ['Unknown'])[0]
            self.play_art_name = self.audio.get('artist', ['Unknown'])[0]
            try:
                self.img_data = self.audio_tags.get("APIC:").data
            except:
                with open('cover.jpg', 'rb') as f:
                    self.img_data = f.read()
        else:
            with open('cover.jpg', 'rb') as f:
                self.img_data = f.read()
                self.play_song_name = 'Unknown'
                self.play_art_name = 'Unknown'

        play_image_data = io.BytesIO(self.img_data)
        img = CoreImage(play_image_data, ext="jpg").texture
        song_image = Image(allow_stretch=True)
        song_image.texture = img
        self.root.ids.PlayScreen.clear_widgets()
        self.root.ids.PlayScreen.add_widget(
            MDIconButton(icon='chevron-left',
                         pos_hint={
                             "center_x": 0.05,
                             "center_y": 0.95
                         },
                         on_press=lambda x: self.back_screen()))
        card = MDCard(orientation='vertical',
                      pos_hint={
                          "center_x": 0.5,
                          "center_y": 0.65
                      },
                      size_hint=(None, None),
                      size=(self.win_size * 0.9, self.win_size * 0.9))
        card.add_widget(song_image)
        self.root.ids.PlayScreen.add_widget(card)
        self.root.ids.PlayScreen.add_widget(
            MDLabel(text=self.play_song_name,
                    halign='center',
                    theme_text_color='Custom',
                    text_color=self.theme_cls.primary_color,
                    font_style='H4',
                    bold=True,
                    pos_hint={"top": 0.84}))
        self.root.ids.PlayScreen.add_widget(
            MDLabel(text=self.play_art_name,
                    halign='center',
                    theme_text_color='Secondary',
                    font_style='H6',
                    pos_hint={"top": 0.8}))
        self.play_progress = MDProgressBar(pos_hint={
            'center_x': 0.5,
            'center_y': 0.25
        },
                                           size_hint_x=0.9,
                                           value=0,
                                           color=self.theme_cls.primary_color)
        self.root.ids.PlayScreen.add_widget(self.play_progress)
        self.root.ids.PlayScreen.add_widget(
            MDIconButton(icon="chevron-double-left",
                         pos_hint={
                             "center_x": .15,
                             "center_y": .15
                         },
                         user_font_size="40sp",
                         on_release=lambda x: self.rewind()))
        self.root.ids.PlayScreen.add_widget(
            MDIconButton(icon="chevron-double-right",
                         pos_hint={
                             "center_x": .85,
                             "center_y": .15
                         },
                         user_font_size="40sp",
                         on_release=lambda x: self.forward()))
        self.next_button = MDIconButton(
            icon="skip-next",
            pos_hint={
                "center_x": .65,
                "center_y": .15
            },
            user_font_size="55sp",
            on_release=lambda x: self.play_song(i + 1))
        self.root.ids.PlayScreen.add_widget(self.next_button)
        self.previous_button = (MDIconButton(
            icon="skip-previous",
            pos_hint={
                "center_x": .35,
                "center_y": .15
            },
            user_font_size="55sp",
            on_release=lambda x: self.play_song(i - 1)))
        self.root.ids.PlayScreen.add_widget(self.previous_button)
        self.play_btn = MDFloatingActionButton(
            icon='play',
            pos_hint={
                'center_x': 0.5,
                "center_y": 0.15
            },
            user_font_size="50sp",
            md_bg_color=(1, 1, 1, 1),
            elevation_normal=10,
            on_press=lambda x: self.play_song_offline(i))
        self.root.ids.PlayScreen.add_widget(self.play_btn)
        self.length_stamp = MDLabel(text=self.convert_sec(
            self.sound.getDuration()),
                                    halign='right',
                                    theme_text_color='Secondary',
                                    padding_x='20dp',
                                    pos_hint={"top": 0.725})
        self.root.ids.PlayScreen.add_widget(self.length_stamp)
        self.play_stamp = (MDLabel(text=self.convert_sec(
            self.sound.getCurrentPosition()),
                                   halign='left',
                                   theme_text_color='Secondary',
                                   padding_x='20dp',
                                   pos_hint={"top": 0.725}))
        self.root.ids.PlayScreen.add_widget(self.play_stamp)
        self.play_song_offline(i)

    def play_song_offline(self, i):
        if True:
            if self.play_status == 'pause' or self.play_status == 'stop':
                self.play_btn.icon = 'pause'
                self.play()
                lnth = self.sound.getDuration()
                t2 = threading.Thread(target=self.online_play_bar,
                                      args=(lnth, i))
                t2.start()
            elif self.play_status == 'play':
                self.play_btn.icon = 'play'
                self.pause()
        else:
            time.sleep(0.5)
            self.play_song_offline

    def convert_sec(self, lnth):
        lnth = lnth / 1000
        try:
            if int(lnth - (60 * (lnth // 60))) < 10:
                return ("{}:0{}".format(int(lnth // 60),
                                        int(lnth - (60 * (lnth // 60)))))
            else:
                return ("{}:{}".format(int(lnth // 60),
                                       int(lnth - (60 * (lnth // 60)))))
        except:
            print('Error: Length is {}'.format(lnth))

    def prepare(self, link):
        print('preparing')
        try:
            self.sound = MediaPlayer()
            self.sound.setDataSource(link)
            self.sound.prepare()
            self.sound.setLooping(False)
        except Exception as e:
            print(e)
            time.sleep(0.25)
            self.prepare(link)
        print('prepared')

    def play(self):
        self.sound.start()
        self.play_status = 'play'

    def pause(self):
        self.sound.pause()
        self.play_status = 'pause'

    def stop(self):
        self.sound.stop()
        self.sound.release()
        self.play_status = 'stop'

    def forward(self):
        self.sound.seekTo(self.sound.getCurrentPosition() + 5000)

    def rewind(self):
        self.sound.seekTo(self.sound.getCurrentPosition() - 5000)

    def callback_for_about(self, *args):
        toast('Opening ' + args[0])
        webbrowser.open_new(args[0])

    def contact_us(self):
        bottom_sheet_menu = MDGridBottomSheet(radius=15, radius_from='top')
        data = [
            {
                "name": "Telegram",
                "icon": "telegram",
                "link": "https://t.me/sangwan5688"
            },
            {
                "name": "Instagram",
                "icon": "instagram",
                "link": "https://www.instagram.com/sangwan5688/"
            },
            {
                "name": "Twitter",
                "icon": "twitter",
                "link": "https://twitter.com/sangwan5688"
            },
            {
                "name":
                "Mail",
                "icon":
                "gmail",
                "link":
                "https://mail.google.com/mail/?view=cm&fs=1&[email protected]&su=Regarding+Mobile+App"
            },
            {
                "name": "Facebook",
                "icon": "facebook",
                "link": "https://www.facebook.com/ankit.sangwan.5688"
            },
        ]
        for item in data:
            bottom_sheet_menu.add_item(
                item["name"],
                lambda x, y=item["link"]: self.callback_for_about(y),
                icon_src=item["icon"],
            )
        bottom_sheet_menu.open()

    def download_song(self):
        if self.status:
            print('started downloading song')
            fname = "{}/{} - {}.m4a".format(self.data_path, self.song_name,
                                            self.artist_name)
            #self.download_bar()
            with requests.get(self.song_dwn_url,
                              stream=True) as r, open(fname, "wb") as f:
                file_size = int(r.headers['Content-Length'])
                total = int(file_size / 1024)
                self.dia.add_widget(
                    MDLabel(text='{:.2f} MB'.format(file_size / (1024 * 1024)),
                            halign='right'))
                for chunk in r.iter_content(chunk_size=1024):
                    if self.status:
                        f.write(chunk)
                        self.download_progress.value += 100 / total
                    else:
                        #print('Download cancelled')
                        break
            print('finished downloading song')
        if self.status:
            self.save_metadata()

    def save_metadata(self):
        with open(self.image_path, 'wb') as f:
            f.write(requests.get(self.image_url).content)
        print('getting metadata')
        audio_path = os.path.join(
            self.data_path, "{} - {}.m4a".format(self.song_name,
                                                 self.artist_name))
        audio = MP4(audio_path)
        audio['\xa9nam'] = self.song_name
        audio['\xa9alb'] = self.album
        audio['aART'] = self.artist_name
        if self.featured_artist != '':
            audio['\xa9ART'] = self.artist_name + ", " + self.featured_artist
        else:
            audio['\xa9ART'] = self.artist_name
        audio['\xa9day'] = self.year
        audio['\xa9gen'] = self.genre
        with open(os.path.join(self.data_path, self.song_id + '.jpg'),
                  "rb") as f:
            audio["covr"] = [
                MP4Cover(f.read(), imageformat=MP4Cover.FORMAT_JPEG)
            ]
        audio.save()
        shutil.move(audio_path, audio_path.replace(self.data_path, self.path))
        print('finished getting metadata')
        #close_btn = MDFlatButton(text="OK", on_release=self.close_dialog)
        self.dia.dismiss()
        os.remove(os.path.join(self.data_path, self.song_id + '.jpg'))
        close_btn = MDIconButton(icon='checkbox-marked-circle-outline',
                                 theme_text_color="Custom",
                                 text_color=self.theme_cls.primary_color,
                                 on_release=self.close_dialog)
        self.dia = MDDialog(title="Download Complete",
                            text="Song Downloaded Successfully!",
                            size_hint=(0.7, 1),
                            buttons=[close_btn])
        self.dia.open()
        #notification.notify(self.song_name +' by '+ self.artist_name, "Download complete")
        #toast("Song Downloaded Successfully!")

    def set_nav_color(self, item):
        for child in self.root.ids.nav_list.children:
            #if child.text_color == self.theme_cls.primary_color:
            #    child.text_color = self.theme_cls.text_color
            #    break
            if child.text == item:
                child.text_color = self.theme_cls.primary_color
                break

    def file_manager_open(self):
        self.file_manager.show(self.path)  # output manager to the screen
        self.manager_open = True

    def select_path(self, path):
        self.exit_manager()
        if os.path.isdir(path):
            self.path = path
            toast("Songs will be downloaded to: " + path)
            self.user_data.put('download_path', path=self.path)
        else:
            toast("No directory selected")

    def exit_manager(self, *args):
        self.manager_open = False
        self.file_manager.close()

    def events(self, instance, keyboard, keycode, text, modifiers):
        #print(keyboard)
        if keyboard in (1001, 27):
            if self.manager_open:
                self.file_manager.back()
            else:
                self.back_screen()
        if keyboard == 13:
            if self.root.ids.screen_manager.current == 'MainScreen':
                self.show_data(self.root.ids.song_name.text)
            else:
                pass
        return True

    def close_dialog(self, obj):
        self.dia.dismiss()
Exemplo n.º 22
0
    def on_pre_enter(self, *args):
        try:
            self.app.add_bottom_canvas()
        except:
            print("on sign up")
        self.app.root.ids['workoutscreen'].tap_target_view = MDTapTargetView(
            widget=self.ids.add_split,
            title_text="Add Splits",
            description_text="press this button to add split days",
            widget_position="right_top",
            target_circle_color=(1, 0, 0))
        if self.app.debug:
            print("entering workout screen")
            print("create mode:", self.create_mode)
            print("edit mode:", self.edit_mode)
            print("temp_workout", self.temp_workout)
            print("workout", self.workout)
            print("workout name", self.workout_name)

        if self.app.root.ids['workoutscreen'].create_mode:
            if self.app.debug:
                print("entering workout screen")
                if self.create_mode:
                    print("In create mode:")
            self.switch_mode("edit")
            self.temp_workout = [[]]
            self.reset_tabs()
            self.reload_page()
            self.app.change_title("Building: " + self.workout_name)
            self.app.root.ids['toolbar'].right_action_items = [[
                'help', lambda x: self.app.show_workout_help()
            ]]

        else:
            self.switch_mode("view")
            screen_manager = self.app.root.ids['screen_manager1']

            if screen_manager.current == "workoutscreen":
                self.app.root.ids['toolbar'].right_action_items = [[
                    'dots-vertical', lambda x: self.app.open_workout_menu()
                ]]
            workout_key_to_view = self.app.workout_key_to_view
            workout_to_view = list(
                self.app.workoutsParsed[workout_key_to_view][0].values())
            workout_name = list(
                self.app.workoutsParsed[workout_key_to_view][0].keys())[0]

            self.workout_name = workout_name
            self.workout_key = workout_key_to_view
            self.workout = workout_to_view[0]
            self.app.change_title(self.workout_name)

            self.temp_workout = copy.deepcopy(self.workout)
            self.reset_tabs()

            if self.app.debug:
                print("In VIEW mode:")
                print("workout to load", workout_to_view)
                print("workout_key", self.workout_key)
                print("temp_workout", self.temp_workout)
                print("workout", self.workout)
                print("workout name", self.workout_name)
                print("TRYING TO RELOAD")

            self.set_split_tabs()
            self.reload_page()
            self.app.root.ids[
                'workoutscreen'].workout_key = self.app.workout_key_to_view
            self.app.root.ids['workoutscreen'].ids["split_tabs"].switch_tab(
                "Split 1")
Exemplo n.º 23
0
class AmazonApp(MDApp):
    def build(self):
        screen = Screen()
        self.theme_cls.theme_style = "Light"
        self.helper_string = Builder.load_string(code_helper)
        screen.add_widget(self.helper_string)
        self.skip_target_view = MDTapTargetView(
            widget=self.helper_string.get_screen(
                'firstwelcome').ids.welcome_skip,
            title_text="Next",
            widget_position="left_bottom",
            title_text_size="20sp",
            description_text="GO next",
            outer_radius='80dp',
            description_text_color=[1, 0, 0, 0],
            outer_circle_alpha=0.40,
            target_radius='40dp')
        self.android_target_view = MDTapTargetView(
            widget=self.helper_string.get_screen(
                'androidinfo').ids.android_info,
            title_text="Hey!!",
            widget_position="center",
            title_text_size="20sp",
            title_position="right_top",
            description_text="I am your assistant\nClick on me",
            outer_radius='180dp',
            description_text_color=[0, 0, 0, 1],
            outer_circle_alpha=0.5,
            target_radius='50dp')
        self.skip_target_view.start()
        self.android_target_view.start()

        #self.dob initialize
        self.dob_entered = True
        return screen

    def theme_switcher(self):
        if self.theme_cls.theme_style == "Dark":
            self.theme_cls.theme_style = "Light"
        else:
            self.theme_cls.theme_style = "Dark"

    def tap_target_stop(self):
        self.skip_target_view.stop()

    def android_info_targerview_stop(self):
        self.android_target_view.stop()

    def help_chip(self, instance, value):
        help_cancel_btn_first = MDIconButton(
            icon='checkbox-marked-circle-outline',
            on_release=self.help_close_dialog_btn)
        self.help_dialog = MDDialog(
            title='Help',
            text=
            'Little android is your assistant\nClick the android for more Info',
            size_hint=(0.7, 0.1),
            buttons=[help_cancel_btn_first])
        self.help_dialog.open()

    def help_close_dialog_btn(self, obj):
        self.help_dialog.dismiss()

    def username_checker(self):
        username_check_false = True
        username_text_data = self.helper_string.get_screen(
            'usernamescreen').ids.username_text.text
        # print(username_text_data)
        try:
            int(username_text_data)
        except:
            username_check_false = False
        if username_check_false or username_text_data.split() == []:
            cancel_btn_username_dialogue = MDFlatButton(
                text='Retry', on_release=self.close_username_dialog)
            self.username_dialoge = MDDialog(
                title='Invalid Username',
                text='Please Enter a valid Username',
                size_hint=(0.7, 0.2),
                buttons=[cancel_btn_username_dialogue])
            self.username_dialoge.open()
        else:
            screen_usernamescreen = self.helper_string.get_screen(
                'usernamescreen')
            screen_usernamescreen.ids.username_enter.disabled = False
            screen_usernamescreen.ids.username_check_extra_button.icon = 'account-check-outline'
            screen_usernamescreen.ids.username_check_btn.text_color = [
                1, 1, 1, 0
            ]
            screen_usernamescreen.ids.username_check_btn.md_bg_color = [
                1, 1, 1, 0
            ]
            screen_usernamescreen.ids.username_check_extra_button.text_color = self.theme_cls.primary_color
            screen_usernamescreen.ids.username_check_extra_button.pos_hint = {
                'center_x': 0.5,
                'center_y': 0.62
            }
            screen_usernamescreen.ids.username_check_extra_button.user_font_size = '60sp'

    def close_username_dialog(self, obj):
        self.username_dialoge.dismiss()


# DOB Picker
#self.dob for Date of birth

    def show_date_picker(self):
        date_dialog = MDDatePicker(
            callback=self.get_date,
            year=1999,
            month=1,
            day=1,
        )
        date_dialog.open()

    def get_date(self, date):
        self.dob = date
        dob_input_screen_selector = self.helper_string.get_screen('dobinput')
        #here i put the next button disbaled as False so user can enter in that window
        dob_input_screen_selector.ids.dob_enter.disabled = False
        dob_input_screen_selector.ids.account_shield.icon = 'shield-account'
        dob_input_screen_selector.ids.dob.text = str(self.dob)
        dob_input_screen_selector.ids.secure.text_color = [0, 1, 0, 0.7]
Exemplo n.º 24
0
class MyApp(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        Window.bind(on_keyboard=self.events)
        self.manager_open = False
        self.file_manager = MDFileManager(
            exit_manager=self.exit_manager,
            select_path=self.select_path,
            preview=True,
        )
    
    icons = list(md_icons.keys())[0:30]
    data = {
        'language-python': 'Python',
        'language-php': 'PHP',
        'language-cpp': 'C++',
    }
    def build(self):
        self.theme_cls.theme_style = "Dark"  # "Light"
        self.theme_cls.primary_palette = "Green"  # "Purple", "Red"
        self.theme_cls.primary_hue = "A700"  # "500"
        self.theme_cls.accent_palette = 'Lime'
        speed_dial = MDFloatingActionButtonSpeedDial()
        speed_dial.hint_animation= True
        speed_dial.right_pad = True
        speed_dial.data = self.data
        speed_dial.root_button_anim = True
        screen= Builder.load_string(kv)
        screen.add_widget(speed_dial)
        self.tap_target_view = MDTapTargetView(
            widget=screen.ids.button,
            title_text="Add Trip",
            description_text="Let people know where are you heading",
            widget_position="left_bottom",
        )
        
        return screen

    def on_start(self):
        for name_tab in self.icons:
            self.root.ids.tabs.add_widget(Tab(text=name_tab))

    def on_tab_switch(
        self, instance_tabs, instance_tab, instance_tab_label, tab_text
    ):
        '''Called when switching tabs.

        :type instance_tabs: <kivymd.uix.tab.MDTabs object>;
        :param instance_tab: <__main__.Tab object>;
        :param instance_tab_label: <kivymd.uix.tab.MDTabsLabel object>;
        :param tab_text: text or name icon of tab;
        '''

        count_icon = [k for k, v in md_icons.items() if v == tab_text]
        instance_tab.ids.icon.icon = count_icon[0]

    def tap_target_start(self):
        if self.tap_target_view.state == "close":
            self.tap_target_view.start()
        else:
            self.tap_target_view.stop()

    def set_list(self):
        async def set_list():
            names_icons_list = list(md_icons.keys())[self.x:self.y]
            for name_icon in names_icons_list:
                await asynckivy.sleep(0)
                self.screen.ids.box.add_widget(
                    ItemForList(icon=name_icon, text=name_icon))
        asynckivy.start(set_list())

    def refresh_callback(self, *args):
        '''A method that updates the state of your application
        while the spinner remains on the screen.'''

        def refresh_callback(interval):
            self.screen.ids.box.clear_widgets()
            if self.x == 0:
                self.x, self.y = 15, 30
            else:
                self.x, self.y = 0, 15
            self.set_list()
            self.screen.ids.refresh_layout.refresh_done()
            self.tick = 0

        Clock.schedule_once(refresh_callback, 1)

    def file_manager_open(self):
        self.file_manager.show('/')  # output manager to the screen
        self.manager_open = True

    def select_path(self, path):
        '''It will be called when you click on the file name
        or the catalog selection button.

        :type path: str;
        :param path: path to the selected directory or file;
        '''

        self.exit_manager()
        toast(path)

    def exit_manager(self, *args):
        '''Called when the user reaches the root of the directory tree.'''

        self.manager_open = False
        self.file_manager.close()

    def events(self, instance, keyboard, keycode, text, modifiers):
        '''Called when buttons are pressed on the mobile device.'''

        if keyboard in (1001, 27):
            if self.manager_open:
                self.file_manager.back()
        return True
Exemplo n.º 25
0
    def on_enter(self):
        self.ids.lbl.opacity = 0
        self.ids.logo.opacity = 1
        self._complete = False

        ttv4 = MDTapTargetView(
            widget=self.ids.add_btn,
            outer_radius=dp(320),
            cancelable=True,
            outer_circle_color=self.app.theme_cls.primary_color[:-1],
            outer_circle_alpha=0.9,
            title_text="This is an add button",
            description_text="You can cancel it by clicking outside",
            widget_position="left_bottom",
        )
        ttv4.bind(on_close=self.complete)

        ttv3 = MDTapTargetView(
            widget=self.ids.info_btn,
            outer_radius=dp(440),
            outer_circle_color=self.app.theme_cls.primary_color[:-1],
            outer_circle_alpha=0.8,
            target_circle_color=[255 / 255, 34 / 255, 212 / 255],
            title_text="This is the info button",
            description_text="No information available yet!",
            widget_position="center",
            title_position="left_bottom",
        )
        ttv3.bind(on_close=ttv4.start)

        ttv2 = MDTapTargetView(
            widget=self.ids.search_btn,
            outer_circle_color=[155 / 255, 89 / 255, 182 / 255],
            target_circle_color=[0.2, 0.2, 0.2],
            title_text="This is the search button",
            description_text="It won't search anything for now.",
            widget_position="center",
            title_position="left_bottom",
        )
        ttv2.bind(on_close=ttv3.start)

        ttv1 = MDTapTargetView(
            widget=self.ids.menu_btn,
            outer_circle_color=self.app.theme_cls.primary_color[:-1],
            outer_circle_alpha=0.85,
            title_text="Menu Button",
            description_text="Opens up the drawer",
            widget_position="center",
            title_position="right_bottom",
        )
        ttv1.bind(on_close=ttv2.start)
        ttv1.start()
Exemplo n.º 26
0
class WelcomeScreen(Screen):

    def __init__(self, **kwargs):
        Builder.load_file('kvs/WelcomeScreen.kv')
        super(WelcomeScreen, self).__init__(**kwargs)

        # timeout variables
        self.timeout_event = None
        self.timeout_time = 30  # Seconds

        # connect tap-target-view
        self.tap_target_view = MDTapTargetView(
            widget=self.ids.info,
            title_text="Version Information",
            description_text=f"Build {App.get_running_app().build_version}\n",
            widget_position="right_bottom"
        )

    def on_pre_enter(self, *args):
        self.ids.label.text = App.get_running_app().active_user

    #
    # performed upon each screen entry
    #
    def on_enter(self, *args):
        # Set timer of duration @timeout_time
        self.timeout_event = Clock.schedule_once(self.on_timeout, self.timeout_time)

    #
    # callback function on timeout
    #
    def on_timeout(self, dt):
        self.on_cancel()

    #
    # when the screen is touched, we restart the timer
    #
    def on_touch_up(self, touch):
        self.timeout_event.cancel()
        self.on_enter()

    #
    # Called when the stop button is pressed
    #
    def on_cancel(self):
        self.manager.transition = SlideTransition(direction='right')
        # Switch back to the default screen to welcome a new user
        self.manager.current = Screens.DEFAULT_SCREEN.value

    #
    # Called when buy is pressed
    #
    def on_buy(self):
        self.manager.transition = SlideTransition(direction='left')
        self.manager.get_screen(Screens.PRODUCT_SCREEN.value).user_name = self.ids.label.text
        self.manager.current = Screens.PRODUCT_SCREEN.value

    def on_touch_move(self, touch):
        if touch.dx > 0:
            self.on_cancel()
        elif touch.dx < 0:
            self.on_buy()

    #
    # Opens the little information screen at the right bottom
    #
    def tap_target_start(self):
        if self.tap_target_view.state == "close":
            self.tap_target_view.start()
        else:
            self.tap_target_view.stop()

    def on_leave(self, *args):
        self.timeout_event.cancel()

        # If tap target view is open, close it
        if self.tap_target_view.state == "open":
            self.tap_target_view.stop()
class DemoApp(MDApp):
    def build(self):
        self.theme_cls.primary_palette = "Blue"  # "BlueGray"
        self.theme_cls.primary_hue = "500"  # "700"
        self.theme_cls.theme_style = "Light"

        screen = Builder.load_string(login_helper)
        self.lusername = Builder.load_string(helpers.lusername_input)
        self.lpassword = Builder.load_string(helpers.lpassword_input)
        button = MDRectangleFlatButton(text='Submit',
                                       pos_hint={
                                           'center_x': 0.5,
                                           'center_y': 0.3
                                       },
                                       on_release=self.log_show_data)
        screen.add_widget(self.lusername)
        screen.add_widget(self.lpassword)
        screen.add_widget(button)
        sm.add_widget(screen)

        screen = Builder.load_string(signup_helper)
        self.username = Builder.load_string(helpers.username_input)
        self.mycontact = Builder.load_string(helpers.mycontact_input)
        self.email = Builder.load_string(helpers.email_input)
        self.password = Builder.load_string(helpers.password_input)
        self.age = Builder.load_string(helpers.age_input)
        button = MDRectangleFlatButton(text='Submit',
                                       pos_hint={
                                           'center_x': 0.5,
                                           'center_y': 0.2
                                       },
                                       on_release=self.sign_show_data)

        screen.add_widget(self.username)
        screen.add_widget(self.mycontact)
        screen.add_widget(self.email)
        screen.add_widget(self.password)
        screen.add_widget(self.age)
        screen.add_widget(button)
        sm.add_widget(screen)

        screen = Builder.load_string(navigation_helper)
        sm.add_widget(screen)

        screen = Builder.load_string(screen_helper)
        self.abusername = Builder.load_string(helpers.abusername_input)
        self.contact = Builder.load_string(helpers.contact_input)
        self.reason = Builder.load_string(helpers.reason_input)
        button = MDRectangleFlatButton(text='Submit',
                                       pos_hint={
                                           'center_x': 0.5,
                                           'center_y': 0.3
                                       },
                                       on_release=self.show_data)
        screen.add_widget(self.abusername)
        screen.add_widget(self.contact)
        screen.add_widget(self.reason)
        screen.add_widget(button)
        sm.add_widget(screen)
        screen = Builder.load_string(newsscraping)
        self.tap_target_view = MDTapTargetView(
            widget=screen.ids.button1,
            title_text="Teens having \nat least 1 social \nmedia profile",
            description_text="   75%                  ",
            widget_position="center",
            title_position="right_top",
            title_text_size="20sp",
            outer_radius=250,
        )

        sm.add_widget(screen)
        screen = Builder.load_string(conv_upload)
        sm.add_widget(screen)

        screen = Builder.load_string(screen_helper4)
        sm.add_widget(screen)
        screen = Builder.load_string(screen_helper5)
        sm.add_widget(screen)
        screen = Builder.load_string(screen_helper6)
        sm.add_widget(screen)

        return sm

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        Window.bind(on_keyboard=self.events)
        self.manager_open = False
        self.file_manager = MDFileManager(
            exit_manager=self.exit_manager,
            select_path=self.select_path,
            ext=[".txt", ".py", "kv"],
        )

    # Sign up validation
    def sign_show_data(self, obj):

        if self.username.text != "" and self.mycontact.text != "" and self.email.text != "" and self.password.text != "":
            if len(self.mycontact.text) == 10 and self.mycontact.text.isdigit(
            ) and self.age.text.isdigit():
                if re.search(regex, self.email.text):
                    if len(self.password.text) >= 8:
                        print("USERNAME- " + self.username.text)

                        print("CONTACT NUMBER- " + self.mycontact.text)

                        print("EMAIL- " + self.email.text)
                        print("PASSWORD- " + self.password.text)
                        print("AGE- " + self.age.text)
                        # self.reason.text, self.contact.text, self.username.text = ""
                        # self.username.text = ""
                        # self.mycontact.text = ""
                        self.email.text = ""
                        # self.age.text = ""
                        user_error = ""
                    else:
                        user_error = "Please enter a valid password"
                else:
                    user_error = "Please enter a valid email id"
            else:
                user_error = "Please enter a valid contact number."

        else:
            user_error = "Please enter the required fields"
        if user_error == "":
            sm.switch_to(Builder.load_string(navigation_helper))
        else:
            self.dialog = MDDialog(text=user_error,
                                   size_hint=(0.8, 1),
                                   buttons=[
                                       MDFlatButton(
                                           text='Close',
                                           on_release=self.close_dialog)
                                   ])
            self.dialog.open()

    # Report portal validation
    def show_data(self, obj):

        if self.contact.text != "" and self.reason.text != "":
            if len(self.contact.text) == 10 and self.contact.text.isdigit():
                print("ABUSER NAME- " + self.abusername.text)
                print(self.username.text, self.mycontact.text)
                print("CONTACT NUMBER- " + self.contact.text)
                print("REASON- " + self.reason.text)
                mail.main_func(self.username.text, self.mycontact.text,
                               self.abusername.text, self.contact.text,
                               self.reason.text, "message")
                self.abusername.text = ""
                self.contact.text = ""
                self.reason.text = ""
                user_error = "Your response has been noted. The immediate responders will contact you soon."
            else:
                user_error = "Please enter a valid contact number."
        else:
            user_error = "Please enter the required fields"
        self.dialog = MDDialog(
            text=user_error,
            size_hint=(0.8, 1),
            buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)])
        self.dialog.open()

    def close_dialog(self, obj):
        self.dialog.dismiss()
        # do stuff after closing the dialog

    def info(self):
        self.dialog = MDDialog(
            text=
            'The information entered below will be forwarded to the respective authorities.',
            size_hint=(0.8, 1),
            buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)])
        self.dialog.open()

    # Login validation
    def log_show_data(self, obj):
        if self.lusername.text != "" and self.lpassword.text != "":
            if len(self.lpassword.text) >= 8:
                sm.switch_to(Builder.load_string(navigation_helper))
            else:
                user_error = "Incorrect password. Please try again"
                self.dialog = MDDialog(text=user_error,
                                       size_hint=(0.8, 1),
                                       buttons=[
                                           MDFlatButton(
                                               text='Close',
                                               on_release=self.close_dialog),
                                       ])

                self.dialog.open()

        else:
            user_error = "Please enter the required details"
            self.dialog = MDDialog(text=user_error,
                                   size_hint=(0.8, 1),
                                   buttons=[
                                       MDFlatButton(
                                           text='Close',
                                           on_release=self.close_dialog),
                                   ])

            self.dialog.open()

    def close_dialog1(self, obj):
        self.dialog.dismiss()

        # do stuff after closing the dialog

    def tap_target_start1(self):
        if self.tap_target_view.state == "close":
            self.tap_target_view.start()
        else:
            self.tap_target_view.stop()

    def tap_target_start2(self):
        if self.tap_target_view.state == "close":
            self.tap_target_view.start()
        else:
            self.tap_target_view.stop()

    def info1(self):
        self.dialog = MDDialog(
            text=
            'Sentimental Analysis displays the polarity ie. positive, negative and neutral polarity values of the whole conversation',
            size_hint=(0.9, 0.5),
            radius=[20, 7, 20, 7],
            buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)])
        self.dialog.open()

    def info2(self):
        self.dialog = MDDialog(
            text=
            'Emotional Analysis displays the various emotions and their value of the whole conversation',
            size_hint=(0.9, 0.5),
            radius=[20, 7, 20, 7],
            buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)])
        self.dialog.open()

    def info3(self):
        self.dialog = MDDialog(
            text=
            'Aspect Based Analysis displays the most talked category of the whole conversation',
            size_hint=(0.9, 0.5),
            radius=[20, 7, 20, 7],
            buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)])
        self.dialog.open()

    def info4(self):
        self.dialog = MDDialog(
            text=
            'Analysis on emotions and tones of conversations and visualise the results in the form of graphs.',
            size_hint=(1, 0),
            radius=[20, 7, 20, 7],
            buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)])
        self.dialog.open()

    def infolda(self):
        self.dialog = MDDialog(
            text=
            'Semantic analysis groups words which are used together frequently',
            size_hint=(0.9, 0.5),
            radius=[20, 7, 20, 7],
            buttons=[MDFlatButton(text='Close', on_release=self.close_dialog)])
        self.dialog.open()

    def callback(self, instance):
        print("Button is pressed")
        print('The button % s state is <%s>' % (instance, instance.state))

    def file_manager_open(self):
        self.file_manager.show('/')  # output manager to the screen
        self.file_manager.use_access = True
        self.manager_open = True

    # Read the conversation and prepare conv_anal screen. Also check for grooming if applicable
    def select_path(self, path):
        '''It will be called when you click on the file name
        or the catalog selection button.
        :type path: str;
        :param path: path to the selected directory or file;
        '''
        self.exit_manager()

        global finalpath
        punc = '''/~$%^'''
        # remove '/' from the path
        for ele in path:
            if ele in punc:
                path1 = path.replace(ele, "")
        # path1 -> '/' symbol removed filepath  /Users\Kripa\Desktop\exconvo.txt to Users\Kripa\Desktop\exconvo.txt

        tmplist = path1.split(os.sep)
        # splits the path and is put in the list tmplist
        # Users\Kripa\Desktop\exconvo.txt to ['Users','Kripa','Desktop','exconvo.txt']

        finalpath = ""
        for wrd in tmplist:
            finalpath = finalpath + r"\\" + wrd
        finalpath = "C:" + finalpath
        # print(finalpath)   #C:\\Users\Kripa\Desktop\exconvo.txt
        with open(finalpath, 'r') as in_file:
            stripped = (line.strip() for line in in_file)
            lines = (line.split(",") for line in stripped if line)

            with open('C:\\Users\\Kripa\\Desktop\\convo.csv', 'w',
                      newline='') as out_file:
                writer = csv.writer(out_file)
                writer.writerow(('name', 'msg'))
                writer.writerows(lines)

        ct = 0
        row_ct1 = 0
        row_ct2 = 0
        strname = ""

        # Get no.of messages for both users
        with open("C:\\Users\\Kripa\Desktop\\convo.csv", 'r') as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')

            for row in csv_reader:
                # lets tokenise
                if ct == 0 and row[0] != "name":
                    strname = row[0]
                    ct = ct + 1
                if row[0] == strname:
                    row_ct1 = row_ct1 + 1

                else:
                    row_ct2 = row_ct2 + 1

        screen = Builder.load_string(conv_anal)

        self.tap_target_view = MDTapTargetView(
            widget=screen.ids.button,
            title_text="USER 1      USER 2",
            description_text="   " + str(row_ct1) + "                  " +
            str(row_ct2) + " \nMESSAGES    MESSAGES",
            widget_position="center",
            title_position="right_top",
            title_text_size="20sp",
            outer_radius=250,
        )

        sm.add_widget(screen)

        # GROOMING
        if int(self.age.text) < 18:
            with open("C:\\Users\\Kripa\Desktop\\convo.csv") as csv_file:
                csv_reader = csv.reader(csv_file, delimiter=',')
                pred_name = ""
                p_ct = 0
                for row in csv_reader:
                    if p_ct == 0 and row[0] != "name" and row[
                            0] != self.username.text:
                        pred_name = row[0]
                        p_ct = p_ct + 1
                    row[1] = row[1].lower()  # convert to lowercase

                    lemr = ""
                    for word in row[1].split():  # Lemmatisation
                        lem = (lemmatizer.lemmatize(word, pos="v"))
                        lem = (lemmatizer.lemmatize(lem))
                        lemr = lemr + lem + " "

                    no_punct = ""
                    for char in lemr:  # Remove punctuation
                        if char not in punctuations:
                            no_punct = no_punct + char

                    data = word_tokenize(no_punct)
                    stopWords = set(stopwords.words('english'))
                    wordsFiltered = []

                    for w in data:  # Remove stopwords
                        if w not in stopWords:
                            wordsFiltered.append(w)
                    fp = "C:\\Users\\Kripa\\Desktop\\exconvo2.csv"
                    with open(fp, 'a+', newline='') as out_file:
                        writer = csv.writer(out_file, delimiter=' ')
                        writer.writerow(wordsFiltered[:20])

            # liwc
            def tokenize(text):
                for match in re.finditer(r'\w+', text, re.UNICODE):
                    yield match.group(0)

            parse, category_names = liwc.load_token_parser(
                "C:\\Users\\Kripa\\Desktop\\bigdic.dic")
            cntt = array('i', [0, 0, 0, 0, 0, 0])  # Stages
            predator = "C:\\Users\\Kripa\\Desktop\\exconvo2.csv"
            with open(predator) as csv_file:
                csv_reader = csv.reader(csv_file, delimiter=',')
                ct = 0
                i = 1
                j = 0
                for row in csv_reader:

                    p = row.copy()
                    p1 = listtostring(p).lower()
                    p_token = tokenize(p1)
                    from collections import Counter
                    op1 = Counter(category for token in p_token
                                  for category in parse(token))
                    op = dict(op1)
                    l = list(op.keys())
                    l.sort(reverse=True)
                    if l:
                        j = l[0]
                    if j == "S1":
                        cntt[0] = cntt[0] + 1
                    if j == "S2":
                        cntt[1] = cntt[1] + 1
                    if j == "S3":
                        cntt[2] = cntt[2] + 1
                    if j == "S4":
                        cntt[3] = cntt[3] + 1
                    if j == "S5":
                        cntt[4] = cntt[4] + 1
                    if j == "S6":
                        cntt[5] = cntt[5] + 1
            '''
            cntt[0]=807
            cntt[1]=396
            cntt[2] =87
            cntt[3] =79
            cntt[4] =38
            cntt[5] =226
            '''
            clf = joblib.load('svm.pkl')
            op = clf.predict([cntt])
            if op == [1]:
                mail.main_func(self.username.text, self.mycontact.text,
                               pred_name, "", "", "message1")
                self.dialog = MDDialog(
                    text=
                    "Grooming characteristics detected. Immediate responders have been informed.",
                    size_hint=(0.8, 1),
                    buttons=[
                        MDFlatButton(text='Close',
                                     on_release=self.close_dialog),
                    ])

                self.dialog.open()

        toast(finalpath)
        # return sm
        os.remove("C:\\Users\\Kripa\\Desktop\\exconvo2.csv")

    def exit_manager(self, *args):
        '''Called when the user reaches the root of the directory tree.'''

        self.manager_open = False
        self.file_manager.close()

    def events(self, instance, keyboard, keycode, text, modifiers):
        '''Called when buttons are pressed on the mobile device.'''

        if keyboard in (1001, 27):
            if self.manager_open:
                self.file_manager.back()
        return True

    # Aspect analysis
    def aspect_fn(self):
        with open("C:\\Users\\Kripa\\Desktop\\convo.csv") as file:
            data = list(csv.reader(file))

        strin = " ".join(str(x) for x in data)

        natural_language_understanding.set_service_url(
            'https://api.eu-gb.natural-language-understanding.watson.cloud.ibm.com/instances/c70c1850-5873-495c-b449-d84d30415f06'
        )
        natural_language_understanding.set_disable_ssl_verification(True)
        response = natural_language_understanding.analyze(
            text=strin,
            features=Features(
                categories=CategoriesOptions(limit=3), )).get_result()

        cat1 = response['categories']

        di1 = cat1[0]
        di2 = cat1[1]
        di3 = cat1[2]

        str1 = di1['label']
        str11 = str(di1['score'])
        str2 = di2['label']
        str21 = str(di2['score'])
        str3 = di3['label']
        str31 = str(di3['score'])

        screen = Builder.load_string(screen_helper3)
        screen.ids.aspectlist.add_widget(
            TwoLineListItem(text=str1, secondary_text=str11))
        screen.ids.aspectlist.add_widget(
            TwoLineListItem(text=str2, secondary_text=str21))
        screen.ids.aspectlist.add_widget(
            TwoLineListItem(text=str3, secondary_text=str31))

        sm.add_widget(screen)

    # Sentiment and emotiona enalysis
    def emo_fn(self):
        cn = cp = cng = e1 = e2 = e3 = e4 = e5 = 0
        with open("C:\\Users\\Kripa\\Desktop\\convo.csv") as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')
            for row in csv_reader:
                j = 0
                row = listtostring(row)
                response = natural_language_understanding.analyze(
                    text=row,
                    language='en',
                    features=Features(
                        sentiment=SentimentOptions(),
                        emotion=EmotionOptions(),
                    )).get_result()

                sen1 = response.get('sentiment').get('document').get('score')
                sen2 = response.get('sentiment').get('document').get('label')
                if sen1 == 0:
                    cn += 1

                elif sen1 > 0:
                    cp += 1

                else:
                    cng += 1
                op = response.get('emotion').get('document').get('emotion')

                # Create a list of tuples sorted by index 1 i.e. value field
                listofTuples = sorted(op.items(),
                                      reverse=True,
                                      key=lambda x: x[1])
                ll = listofTuples[0]
                d = dict(listofTuples)
                for k, v in d.items():
                    d1 = k
                    d2 = v
                    j += 1
                    if j > 0:
                        break
                if d1 == 'sadness':
                    e1 += 1
                elif d1 == 'joy':
                    e2 += 1
                elif d1 == 'fear':
                    e3 += 1
                elif d1 == 'disgust':
                    e4 += 1
                else:
                    e5 += 1

        s = s1 = 0
        s = cn + cng + cp
        pp = (cp * 100) / s
        ngp = (cng * 100) / s
        np = (cn * 100) / s
        s1 = e1 + e2 + e3 + e4 + e5
        e1p = (e1 * 100) / s1
        e2p = (e2 * 100) / s1
        e3p = (e3 * 100) / s1
        e4p = (e4 * 100) / s1
        e5p = (e5 * 100) / s1

        screen = Builder.load_string(screen_helper1)

        neutral = "Neutral: " + str(round(np, 2))
        pos = "Positive: " + str(round(pp, 2))
        neg = "Negative: " + str(round(ngp, 2))

        screen.ids.sentimentlist.add_widget(OneLineListItem(text=neutral, ))
        screen.ids.sentimentlist.add_widget(OneLineListItem(text=pos, ))
        screen.ids.sentimentlist.add_widget(OneLineListItem(text=neg, ))

        sm.add_widget(screen)

        screen = Builder.load_string(screen_helper2)

        sad = "Sad: " + str(round(e1p, 2))
        joy = "Joy: " + str(round(e2p, 2))
        fear = "Fear: " + str(round(e3p, 2))
        disgust = "Disgust: " + str(round(e4p, 2))
        angry = "Angry: " + str(round(e5p, 2))

        screen.ids.emotionallist.add_widget(OneLineListItem(text=sad, ))
        screen.ids.emotionallist.add_widget(OneLineListItem(text=joy, ))
        screen.ids.emotionallist.add_widget(OneLineListItem(text=fear, ))
        screen.ids.emotionallist.add_widget(OneLineListItem(text=disgust, ))
        screen.ids.emotionallist.add_widget(OneLineListItem(text=angry, ))

        sm.add_widget(screen)

    # Semantic analysis
    def lda_fn(self):
        screen = Builder.load_string(screen_helperlda)

        with open("C:\\Users\\Kripa\Desktop\\convo.csv", 'r') as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')

            for row in csv_reader:
                # lets tokenise

                raw = row[1]
                tokens = tokenizer.tokenize(raw)

                # remove stopwords
                stopped_tokens = [i for i in tokens if not i in en_stop]

                tagged = nltk.pos_tag(stopped_tokens)

                for word, tag in tagged:
                    w_tag = get_wordnet_pos(tag)
                    if w_tag is None:
                        lemmatized_tokens = [lemmatizer.lemmatize(word)]
                    else:
                        lemmatized_tokens = [
                            lemmatizer.lemmatize(word, pos=w_tag)
                        ]

                    texts.append(lemmatized_tokens)

        # create_dict
        id2word = corpora.Dictionary(texts)

        # convert to document-term matrix
        corpus = [id2word.doc2bow(text) for text in texts]

        # generate lda
        lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus,
                                                    id2word=id2word,
                                                    num_topics=5,
                                                    passes=20)
        # print(lda_model.print_topics(num_topics=5))

        top_words_per_topic = []

        # puting ouput to a csv file!
        for t in range(lda_model.num_topics):
            top_words_per_topic.extend([(t, ) + x
                                        for x in lda_model.show_topic(t)])

        x = pd.DataFrame(top_words_per_topic, columns=['Tno', 'Word', 'P'])
        # .to_csv('C:\\Users\\Kripa\Desktop\\top_words.csv')
        y = x['Word']

        name1 = []
        for ele in y:
            name1.append(ele)

        screen.ids.ldalist.add_widget(
            ThreeLineListItem(text="Group 1",
                              secondary_text=name1[0] + "," + name1[1] + "," +
                              name1[2] + "," + name1[3] + "," + name1[4] + ",",
                              tertiary_text=name1[5] + "," + name1[6] + "," +
                              name1[7] + "," + name1[8] + "," + name1[9]))
        screen.ids.ldalist.add_widget(
            ThreeLineListItem(
                text="Group 2",
                secondary_text=name1[10] + "," + name1[11] + "," + name1[12] +
                "," + name1[13] + "," + name1[14] + ",",
                tertiary_text=name1[15] + "," + name1[16] + "," + name1[17] +
                "," + name1[18] + "," + name1[19]))
        screen.ids.ldalist.add_widget(
            ThreeLineListItem(
                text="Group 3",
                secondary_text=name1[20] + "," + name1[21] + "," + name1[22] +
                "," + name1[23] + "," + name1[24] + ",",
                tertiary_text=name1[25] + "," + name1[26] + "," + name1[27] +
                "," + name1[28] + "," + name1[29]))

        sm.add_widget(screen)
    def build(self):
        self.theme_cls.primary_palette = "Blue"  # "BlueGray"
        self.theme_cls.primary_hue = "500"  # "700"
        self.theme_cls.theme_style = "Light"

        screen = Builder.load_string(login_helper)
        self.lusername = Builder.load_string(helpers.lusername_input)
        self.lpassword = Builder.load_string(helpers.lpassword_input)
        button = MDRectangleFlatButton(text='Submit',
                                       pos_hint={
                                           'center_x': 0.5,
                                           'center_y': 0.3
                                       },
                                       on_release=self.log_show_data)
        screen.add_widget(self.lusername)
        screen.add_widget(self.lpassword)
        screen.add_widget(button)
        sm.add_widget(screen)

        screen = Builder.load_string(signup_helper)
        self.username = Builder.load_string(helpers.username_input)
        self.mycontact = Builder.load_string(helpers.mycontact_input)
        self.email = Builder.load_string(helpers.email_input)
        self.password = Builder.load_string(helpers.password_input)
        self.age = Builder.load_string(helpers.age_input)
        button = MDRectangleFlatButton(text='Submit',
                                       pos_hint={
                                           'center_x': 0.5,
                                           'center_y': 0.2
                                       },
                                       on_release=self.sign_show_data)

        screen.add_widget(self.username)
        screen.add_widget(self.mycontact)
        screen.add_widget(self.email)
        screen.add_widget(self.password)
        screen.add_widget(self.age)
        screen.add_widget(button)
        sm.add_widget(screen)

        screen = Builder.load_string(navigation_helper)
        sm.add_widget(screen)

        screen = Builder.load_string(screen_helper)
        self.abusername = Builder.load_string(helpers.abusername_input)
        self.contact = Builder.load_string(helpers.contact_input)
        self.reason = Builder.load_string(helpers.reason_input)
        button = MDRectangleFlatButton(text='Submit',
                                       pos_hint={
                                           'center_x': 0.5,
                                           'center_y': 0.3
                                       },
                                       on_release=self.show_data)
        screen.add_widget(self.abusername)
        screen.add_widget(self.contact)
        screen.add_widget(self.reason)
        screen.add_widget(button)
        sm.add_widget(screen)
        screen = Builder.load_string(newsscraping)
        self.tap_target_view = MDTapTargetView(
            widget=screen.ids.button1,
            title_text="Teens having \nat least 1 social \nmedia profile",
            description_text="   75%                  ",
            widget_position="center",
            title_position="right_top",
            title_text_size="20sp",
            outer_radius=250,
        )

        sm.add_widget(screen)
        screen = Builder.load_string(conv_upload)
        sm.add_widget(screen)

        screen = Builder.load_string(screen_helper4)
        sm.add_widget(screen)
        screen = Builder.load_string(screen_helper5)
        sm.add_widget(screen)
        screen = Builder.load_string(screen_helper6)
        sm.add_widget(screen)

        return sm
    def select_path(self, path):
        '''It will be called when you click on the file name
        or the catalog selection button.
        :type path: str;
        :param path: path to the selected directory or file;
        '''
        self.exit_manager()

        global finalpath
        punc = '''/~$%^'''
        # remove '/' from the path
        for ele in path:
            if ele in punc:
                path1 = path.replace(ele, "")
        # path1 -> '/' symbol removed filepath  /Users\Kripa\Desktop\exconvo.txt to Users\Kripa\Desktop\exconvo.txt

        tmplist = path1.split(os.sep)
        # splits the path and is put in the list tmplist
        # Users\Kripa\Desktop\exconvo.txt to ['Users','Kripa','Desktop','exconvo.txt']

        finalpath = ""
        for wrd in tmplist:
            finalpath = finalpath + r"\\" + wrd
        finalpath = "C:" + finalpath
        # print(finalpath)   #C:\\Users\Kripa\Desktop\exconvo.txt
        with open(finalpath, 'r') as in_file:
            stripped = (line.strip() for line in in_file)
            lines = (line.split(",") for line in stripped if line)

            with open('C:\\Users\\Kripa\\Desktop\\convo.csv', 'w',
                      newline='') as out_file:
                writer = csv.writer(out_file)
                writer.writerow(('name', 'msg'))
                writer.writerows(lines)

        ct = 0
        row_ct1 = 0
        row_ct2 = 0
        strname = ""

        # Get no.of messages for both users
        with open("C:\\Users\\Kripa\Desktop\\convo.csv", 'r') as csv_file:
            csv_reader = csv.reader(csv_file, delimiter=',')

            for row in csv_reader:
                # lets tokenise
                if ct == 0 and row[0] != "name":
                    strname = row[0]
                    ct = ct + 1
                if row[0] == strname:
                    row_ct1 = row_ct1 + 1

                else:
                    row_ct2 = row_ct2 + 1

        screen = Builder.load_string(conv_anal)

        self.tap_target_view = MDTapTargetView(
            widget=screen.ids.button,
            title_text="USER 1      USER 2",
            description_text="   " + str(row_ct1) + "                  " +
            str(row_ct2) + " \nMESSAGES    MESSAGES",
            widget_position="center",
            title_position="right_top",
            title_text_size="20sp",
            outer_radius=250,
        )

        sm.add_widget(screen)

        # GROOMING
        if int(self.age.text) < 18:
            with open("C:\\Users\\Kripa\Desktop\\convo.csv") as csv_file:
                csv_reader = csv.reader(csv_file, delimiter=',')
                pred_name = ""
                p_ct = 0
                for row in csv_reader:
                    if p_ct == 0 and row[0] != "name" and row[
                            0] != self.username.text:
                        pred_name = row[0]
                        p_ct = p_ct + 1
                    row[1] = row[1].lower()  # convert to lowercase

                    lemr = ""
                    for word in row[1].split():  # Lemmatisation
                        lem = (lemmatizer.lemmatize(word, pos="v"))
                        lem = (lemmatizer.lemmatize(lem))
                        lemr = lemr + lem + " "

                    no_punct = ""
                    for char in lemr:  # Remove punctuation
                        if char not in punctuations:
                            no_punct = no_punct + char

                    data = word_tokenize(no_punct)
                    stopWords = set(stopwords.words('english'))
                    wordsFiltered = []

                    for w in data:  # Remove stopwords
                        if w not in stopWords:
                            wordsFiltered.append(w)
                    fp = "C:\\Users\\Kripa\\Desktop\\exconvo2.csv"
                    with open(fp, 'a+', newline='') as out_file:
                        writer = csv.writer(out_file, delimiter=' ')
                        writer.writerow(wordsFiltered[:20])

            # liwc
            def tokenize(text):
                for match in re.finditer(r'\w+', text, re.UNICODE):
                    yield match.group(0)

            parse, category_names = liwc.load_token_parser(
                "C:\\Users\\Kripa\\Desktop\\bigdic.dic")
            cntt = array('i', [0, 0, 0, 0, 0, 0])  # Stages
            predator = "C:\\Users\\Kripa\\Desktop\\exconvo2.csv"
            with open(predator) as csv_file:
                csv_reader = csv.reader(csv_file, delimiter=',')
                ct = 0
                i = 1
                j = 0
                for row in csv_reader:

                    p = row.copy()
                    p1 = listtostring(p).lower()
                    p_token = tokenize(p1)
                    from collections import Counter
                    op1 = Counter(category for token in p_token
                                  for category in parse(token))
                    op = dict(op1)
                    l = list(op.keys())
                    l.sort(reverse=True)
                    if l:
                        j = l[0]
                    if j == "S1":
                        cntt[0] = cntt[0] + 1
                    if j == "S2":
                        cntt[1] = cntt[1] + 1
                    if j == "S3":
                        cntt[2] = cntt[2] + 1
                    if j == "S4":
                        cntt[3] = cntt[3] + 1
                    if j == "S5":
                        cntt[4] = cntt[4] + 1
                    if j == "S6":
                        cntt[5] = cntt[5] + 1
            '''
            cntt[0]=807
            cntt[1]=396
            cntt[2] =87
            cntt[3] =79
            cntt[4] =38
            cntt[5] =226
            '''
            clf = joblib.load('svm.pkl')
            op = clf.predict([cntt])
            if op == [1]:
                mail.main_func(self.username.text, self.mycontact.text,
                               pred_name, "", "", "message1")
                self.dialog = MDDialog(
                    text=
                    "Grooming characteristics detected. Immediate responders have been informed.",
                    size_hint=(0.8, 1),
                    buttons=[
                        MDFlatButton(text='Close',
                                     on_release=self.close_dialog),
                    ])

                self.dialog.open()

        toast(finalpath)
        # return sm
        os.remove("C:\\Users\\Kripa\\Desktop\\exconvo2.csv")
Exemplo n.º 30
0
class ProfileScreen(Screen):
    def Brow(self):
        window = Tk()
        try:
            os.chdir(working)
            shutil.move(os.path.join(os.path.expandvars("%userprofile%"), "Desktop" + "/Locker"),
                        os.getcwd() + "/output/public/")
        except:
            pass
        try:
            os.chdir("output/public/")
        except:
            pass
        window.withdraw()
        try:
            dwldDirectory = askopenfilename()
            try:
                os.chdir("output/public/")
                os.remove("unlock.bat")
                os.remove("unlock.txt")
            except:
                pass
            print(os.getcwd())
            fob = open('unlock.txt', 'w')
            fob.write("@ECHO OFF\n"
                      "attrib -h -s "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n'
                      "ren "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"'" Locker\n"
                      "echo Folder Unlocked successfully\n"
                      "goto End\n"
                      ":End")
            fob.close()
            os.rename("unlock.txt", "unlock.bat")
            os.startfile("unlock.bat")
            time.sleep(1)
            if os.path.exists("Locker"):
                print("remove")
                os.remove("unlock.bat")
            try:
                shutil.move(dwldDirectory, "Locker/locked files/")
                time.sleep(1)
                fob = open('lock.txt', 'w')
                fob.write("@ECHO OFF\n"
                          "ren Locker "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n'
                          "attrib +h +s "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n'
                          "echo Folder locked\n"
                          "goto End\n"
                          ":End\n")
                fob.close()
                os.rename("lock.txt", "lock.bat")
                os.startfile("lock.bat")
                time.sleep(1)
                os.remove("lock.bat")
                print("work done")
                try:
                    os.remove("unlock.bat")
                except:
                    pass
                messagebox.showinfo("SUCCESS", "file safely stored in locker")
            except:
                messagebox.showinfo("error",
                                    "unable to export file do it manually or same name file already exist in locker folder)")
                self.lock()
            window.destroy()
        except:
            showinfo("error", "please select the file or same name file already exist in locker folder)")
            print(os.getcwd())
            self.lock()
            pass
    def unlock(self):
        try:
            os.chdir("output/public")
        except:
            pass
        print(os.getcwd())
        fob = open('unlock.txt', 'w')
        fob.write("@ECHO OFF\n"
                  "attrib -h -s "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n'
                  "ren "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"'" Locker\n"
                  "echo Folder Unlocked successfully\n"
                  "goto End\n"
                  ":End")
        fob.close()
        os.rename("unlock.txt", "unlock.bat")
        os.startfile("unlock.bat")
        time.sleep(1)
        if os.path.exists("Locker"):
            print("remove")
            os.remove("unlock.bat")
            shutil.move("Locker",os.path.join(os.path.expandvars("%userprofile%"),"Desktop"))
            time.sleep(1)
            os.startfile(os.path.join(os.path.expandvars("%userprofile%"), "Desktop"+"/Locker"))
    def kick(self):
        if os.path.exists("output/public/Locker"):
            print("loker")
            self.lock()
        elif os.path.exists(os.path.join(os.path.expandvars("%userprofile%"), "Desktop"+"/Locker")):
            print("locker")
            self.lock()
        else:
            self.unlock()
            print("unlock")
    def lock(self):
        try:
            os.chdir("output/public")
        except:
            pass
        try:
            shutil.move(os.path.join(os.path.expandvars("%userprofile%"), "Desktop"+"/Locker"),os.getcwd())
        except:
            pass
        fob = open('lock.txt', 'w')
        fob.write("@ECHO OFF\n"
                  "ren Locker "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n'
                  "attrib +h +s "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n'
                  "echo Folder locked\n"
                  "goto End\n"
                  ":End\n")
        fob.close()
        os.rename("lock.txt", "lock.bat")
        os.startfile("lock.bat")
        time.sleep(1)
        os.remove("lock.bat")
        print("work done")
    def Brow2(self):
        window = Tk()
        try:
            os.chdir(working)
            shutil.move(os.path.join(os.path.expandvars("%userprofile%"), "Desktop"+"/Locker"),os.getcwd()+"/output/public/")
        except:
            pass
        try:
            os.chdir("output/public/")
        except:
            pass
        window.withdraw()
        try:
            dwldDirectory = askdirectory()
            try:
                os.chdir("output/public/")
                os.remove("unlock.bat")
                os.remove("unlock.txt")
            except:
                pass
            print(os.getcwd())
            fob = open('unlock.txt', 'w')
            fob.write("@ECHO OFF\n"
                      "attrib -h -s "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n'
                      "ren "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"'" Locker\n"
                      "echo Folder Unlocked successfully\n"
                      "goto End\n"
                      ":End")
            fob.close()
            os.rename("unlock.txt", "unlock.bat")
            os.startfile("unlock.bat")
            time.sleep(1)
            if os.path.exists("Locker"):
                print("remove")
                os.remove("unlock.bat")
            try:
                shutil.move(dwldDirectory, "Locker/locked folders/")
                time.sleep(1)
                fob = open('lock.txt', 'w')
                fob.write("@ECHO OFF\n"
                          "ren Locker "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n'
                          "attrib +h +s "'"Control Panel.{21EC2020-3AEA-1069-A2DD-08002B30309D}"\n'
                          "echo Folder locked\n"
                          "goto End\n"
                          ":End\n")
                fob.close()
                os.rename("lock.txt", "lock.bat")
                os.startfile("lock.bat")
                time.sleep(1)
                os.remove("lock.bat")
                print("work done")
                try:
                    os.remove("unlock.bat")
                except:
                    pass
                messagebox.showinfo("SUCCESS", "file safely stored in locker")
            except:
                messagebox.showinfo("error", "unable to export file do it manually or same name file already exist in locker folder)")
                self.lock()
            window.destroy()
        except:
            showinfo("error", "please select the file or same name file already exist in locker folder)")
            print(os.getcwd())
            self.lock()
            pass
    def tap_target_start(self):
        self.tap_target_view = MDTapTargetView(
            widget=self.ids['button'],
            title_text="akria",
            description_text="what can i do for you sir?",
            widget_position="center",
            title_position="left_top",
            outer_radius=150,
        )
        if self.tap_target_view.state == "open":
            self.tap_target_view.stop()
        else:
            self.tap_target_view.start()