Esempio n. 1
0
def update_news():
    """[localhost] Atualiza zip das noticias locais do servidor """
    if not env.platform == "windows":
        abort(alert("Esse comando soh executa no servidor (Windows)"))

    # TODO: implementar execucao do scripts/get_sintonia_zip.cmd
    notify("getting done")
def Playvid(url, name):
    dp = xbmcgui.DialogProgress()
    dp.create("Searching webcamlink","Searching webcamlink for:",name)
    count = 0
    for videoid in range(491, 340, -1):
        dp.update(int(count))
        videotest = 'false'
        testurl = 'http://video%s.myfreecams.com:1935/NxServer/mfc_%s.f4v_aac/playlist.m3u8' % (videoid, url)
        if videotest == 'false':
            try: videotest = urllib2.urlopen(testurl)
            except: videotest = 'false'
        count = count + 0.7
        if not videotest == 'false':
            dp.update(100)
            dp.close()
            break
        if dp.iscanceled():
            dp.close()
            break
    if not videotest == 'false':
        videourl = testurl
        iconimage = xbmc.getInfoImage("ListItem.Thumb")
        listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        listitem.setInfo('video', {'Title': name, 'Genre': 'P**n'})
        listitem.setProperty("IsPlayable","true")
        if int(sys.argv[1]) == -1:
            pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            pl.clear()
            pl.add(videourl, listitem)
            xbmc.Player().play(pl)
        else:
            listitem.setPath(str(videourl))
            xbmcplugin.setResolvedUrl(utils.addon_handle, True, listitem)
    else:
        utils.notify('Oh oh','Couldn\'t find a playable webcam link')
Esempio n. 3
0
 def togglePreview(self):
     if self.toggledPreview():
         Window(10000).clearProperty('SR_togglePreview')
         utils.notify(utils.translation(32226))
     else:
         Window(10000).setProperty('SR_togglePreview', '1')
         utils.notify(utils.translation(32227))
Esempio n. 4
0
 def toggle_preset(self):
     if self.preset_button.isSelected():
         self.camera.ptz_add_preset()
         utils.notify('Home Location is now Current Location')
     else:
         self.camera.ptz_delete_preset()
         utils.notify('Home Location is now Default Location')
Esempio n. 5
0
    def fetchFile(self):
        retVal = self.FETCH_NOT_NEEDED
        fetch = False
        if not os.path.exists(
                self.filePath):  # always fetch if file doesn't exist!
            fetch = True
        else:
            interval = int(self.addon.getSetting('xmltv.interval'))
            if interval <> self.INTERVAL_ALWAYS:
                modTime = datetime.datetime.fromtimestamp(
                    os.path.getmtime(self.filePath))
                td = datetime.datetime.now() - modTime
                # need to do it this way cause Android doesn't support .total_seconds() :(
                diff = (td.microseconds +
                        (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
                if ((interval == self.INTERVAL_12 and diff >= 43200)
                        or (interval == self.INTERVAL_24 and diff >= 86400)
                        or (interval == self.INTERVAL_48 and diff >= 172800)):
                    fetch = True
            else:
                fetch = True

        if fetch:

            username = utils.get_setting(addon_id, 'username')
            password = utils.get_setting(addon_id, 'password')
            base64string = base64.encodestring(
                '%s:%s' % (username, password)).replace('\n', '')
            tmpFile = os.path.join(self.basePath, 'tmp')
            f = open(tmpFile, 'wb')

            try:
                request = urllib2.Request(self.fileUrl)
                request.add_header("Authorization", "Basic %s" % base64string)
                tmpData = urllib2.urlopen(request)
                data = tmpData.read()
                if tmpData.info().get('content-encoding') == 'gzip':
                    data = zlib.decompress(data, zlib.MAX_WBITS + 16)
                f.write(data)
                f.close()

            except urllib2.HTTPError, e:
                if e.code == 401:
                    utils.notify(
                        addon_id,
                        'Authorization Error !!! Please Check Your Username and Password'
                    )
                else:
                    utils.notify(addon_id, e)

            if os.path.getsize(tmpFile) > 256:
                if os.path.exists(self.filePath):
                    os.remove(self.filePath)
                os.rename(tmpFile, self.filePath)
                retVal = self.FETCH_OK
                xbmc.log(
                    '[script.ivueguide] file %s was downloaded' %
                    self.filePath, xbmc.LOGDEBUG)
            else:
                retVal = self.FETCH_ERROR
Esempio n. 6
0
    def _populate_record(self, record, data):
        """
        Given mapping of data, copy values to attributes on record.

        Subclasses may override to provide schema validation, selective
        copy of names, and normalization of values if/as necessary.
        """
        changelog = []
        for key, value in data.items():
            if key.startswith('_'):
                continue  # invalid key
            if key == 'record_uid':
                self.record_uid = str(value)
                continue
            try:
                self._type_whitelist_validation(value)
            except ValueError:
                continue  # skip problem name!
            existing_value = getattr(self, key, None)
            if value != existing_value:
                changelog.append(key)
                setattr(record, key, value)
        if changelog:
            record._p_changed = True
            changelog = [
                Attributes(self.RECORD_INTERFACE, name)
                for name in changelog
                ]
            notify(ObjectModifiedEvent(record, *changelog))
 def togglePreview(self):
     if self.toggledPreview():
         Window(10000).clearProperty('SR_togglePreview')
         utils.notify(utils.translation(32226))
     else:
         Window(10000).setProperty('SR_togglePreview', '1')
         utils.notify(utils.translation(32227))
Esempio n. 8
0
def Playvid(username, name):
    try:
        postRequest = {
            'method': 'getRoomData',
            'args[]': 'false',
            'args[]': str(username)
        }
        response = utils.postHtml(
            'http://bongacams.com/tools/amf.php',
            form_data=postRequest,
            headers={'X-Requested-With': 'XMLHttpRequest'},
            compression=False)
    except:
        utils.notify('Oh oh', 'Couldn\'t find a playable webcam link')
        return None

    amf_json = json.loads(response)

    if amf_json['localData']['videoServerUrl'].startswith("//mobile"):
        videourl = 'https:' + amf_json['localData'][
            'videoServerUrl'] + '/hls/stream_' + username + '.m3u8'
    else:
        videourl = 'https:' + amf_json['localData'][
            'videoServerUrl'] + '/hls/stream_' + username + '/playlist.m3u8'

    print(videourl)
    subprocess.Popen('mpv ' + videourl,
                     shell=True,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)
Esempio n. 9
0
    def _store(path, status, items=()):
        notify('STORE', path)
        cache.append((path, status, items))
        stats['store'] += 1

        if len(cache) > CACHE_MAX_SIZE:
            _commit()
Esempio n. 10
0
    def search_movie(self, title, year, imdb_id):
        if "search_tags" not in self._caps:
            notify(translation(32701), image=get_icon_path())
            return []

        movie_search_caps = self._caps["search_tags"]['movie-search']
        if not movie_search_caps['enabled']:
            notify(translation(32702).format("movie"), image=get_icon_path())
            log.warning(
                "Jackett has no movie capabilities, please add a indexer that has movie capabilities. "
                "Falling back to query search...")
            return self.search_query(title + u' ' + year)

        # todo what values are possible for imdb_id?
        movie_params = movie_search_caps["params"]
        request_params = {"t": "movie", "apikey": self._api_key}

        has_imdb_caps = 'imdbid' in movie_params
        log.debug("movie search; imdb_id=%s, has_imdb_caps=%s", imdb_id,
                  has_imdb_caps)
        if imdb_id and has_imdb_caps:
            request_params["imdbid"] = imdb_id
        else:
            request_params["q"] = title + u' ' + year
            log.debug("searching movie with query=%s", request_params["q"])

        return self._do_search_request(request_params)
Esempio n. 11
0
def search_jackett(payload, method):
    jackett = get_client()
    if jackett is None:
        utils.notify(utils.translation(32603), image=utils.get_icon_path())
        return []

    log.debug("Processing %s with Jackett", method)
    if method == 'movie':
        res = jackett.search_movie(payload["search_title"], payload['year'],
                                   payload["imdb_id"])
    elif method == 'season':
        res = jackett.search_season(payload["search_title"], payload["season"],
                                    payload["imdb_id"])
    elif method == 'episode':
        res = jackett.search_episode(payload["search_title"],
                                     payload["season"], payload["episode"],
                                     payload["imdb_id"])
    elif method == 'anime':
        log.warning("jackett provider does not yet support anime search")
        res = []
        log.info("anime payload=%s", repr(payload))
    #     client.search_query(payload["search_title"], payload["season"], payload["episode"], payload["imdb_id"])
    else:
        res = jackett.search_query(payload["search_title"])

    log.debug("%s search returned %d results", method, len(res))

    res = filter_results(method, res)

    return sort_results(res)
Esempio n. 12
0
    def _do_search_request(self, request_params):
        censored_params = request_params.copy()
        censored_key = censored_params['apikey']
        censored_params['apikey'] = "{}{}{}".format(censored_key[0:2],
                                                    "*" * 26,
                                                    censored_key[-4:])
        log.debug('Making a request to Jackett using params %s',
                  repr(censored_params))

        search_resp = self._session.get("all/results/torznab",
                                        params=request_params)
        if search_resp.status_code != httplib.OK:
            notify(translation(32700).format(search_resp.reason),
                   image=get_icon_path())
            log.error("Jackett returned %s", search_resp.reason)
            return []

        err = self.get_error(search_resp.content)
        if err is not None:
            notify(translation(32700).format(err["description"]),
                   image=get_icon_path())
            log.error("got code %s: %s", err["code"], err["description"])
            return []

        log.debug("Jackett returned below response")
        log.debug("===============================")
        log.debug(search_resp.content)
        log.debug("===============================")

        return self._parse_items(search_resp.content)
Esempio n. 13
0
def autostart():
    """
    Starts the cleaning service.
    """
    cleaner = Cleaner()

    service_sleep = 10
    ticker = 0
    delayed_completed = False

    while not xbmc.abortRequested:
        if get_setting(service_enabled):
            scan_interval_ticker = get_setting(scan_interval) * 60 / service_sleep
            delayed_start_ticker = get_setting(delayed_start) * 60 / service_sleep

            if delayed_completed and ticker >= scan_interval_ticker:
                results, exit_status = cleaner.cleanup()
                if results and exit_status == 0:
                    notify(results)
                ticker = 0
            elif not delayed_completed and ticker >= delayed_start_ticker:
                delayed_completed = True
                results, exit_status = cleaner.cleanup()
                if results and exit_status == 0:
                    notify(results)
                ticker = 0

            xbmc.sleep(service_sleep * 1000)
            ticker += 1
        else:
            xbmc.sleep(service_sleep * 1000)

    debug("Abort requested. Terminating.")
    return
Esempio n. 14
0
def autostart():
    """
    Starts the cleaning service.
    """
    cleaner = Cleaner()

    service_sleep = 4  # Lower than 4 causes too much stress on resource limited systems such as RPi
    ticker = 0
    delayed_completed = False

    while not cleaner.monitor.abortRequested():
        if get_setting(service_enabled):
            scan_interval_ticker = get_setting(scan_interval) * 60 / service_sleep
            delayed_start_ticker = get_setting(delayed_start) * 60 / service_sleep

            if delayed_completed and ticker >= scan_interval_ticker:
                results, _ = cleaner.clean_all()
                notify(results)
                ticker = 0
            elif not delayed_completed and ticker >= delayed_start_ticker:
                delayed_completed = True
                results, _ = cleaner.clean_all()
                notify(results)
                ticker = 0

            cleaner.monitor.waitForAbort(service_sleep)
            ticker += 1
        else:
            cleaner.monitor.waitForAbort(service_sleep)

    debug(u"Abort requested. Terminating.")
    return
Esempio n. 15
0
def Playvid(url, name):
    dp = xbmcgui.DialogProgress()
    dp.create("Searching webcamlink","Searching webcamlink for:",name)
    count = 0
    for videoid in range(491, 340, -1):
        dp.update(int(count))
        videotest = 'false'
        testurl = 'http://video%s.myfreecams.com:1935/NxServer/mfc_%s.f4v_aac/playlist.m3u8' % (videoid, url)
        if videotest == 'false':
            try: videotest = urllib2.urlopen(testurl)
            except: videotest = 'false'
        count = count + 0.7
        if not videotest == 'false':
            dp.update(100)
            dp.close()
            break
        if dp.iscanceled():
            dp.close()
            break
    if not videotest == 'false':
        videourl = testurl
        iconimage = xbmc.getInfoImage("ListItem.Thumb")
        listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        listitem.setInfo('video', {'Title': name, 'Genre': 'P**n'})
        listitem.setProperty("IsPlayable","true")
        if int(sys.argv[1]) == -1:
            pl = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
            pl.clear()
            pl.add(videourl, listitem)
            xbmc.Player().play(pl)
        else:
            listitem.setPath(str(videourl))
            xbmcplugin.setResolvedUrl(utils.addon_handle, True, listitem)
    else:
        utils.notify('Oh oh','Couldn\'t find a playable webcam link')
Esempio n. 16
0
def autostart():
    """
    Starts the cleaning service.
    """
    cleaner = Cleaner()

    service_sleep = 4  # Lower than 4 causes too much stress on resource limited systems such as RPi
    ticker = 0
    delayed_completed = False

    while not cleaner.monitor.abortRequested():
        if get_setting(service_enabled):
            scan_interval_ticker = get_setting(scan_interval) * 60 / service_sleep
            delayed_start_ticker = get_setting(delayed_start) * 60 / service_sleep

            if delayed_completed and ticker >= scan_interval_ticker:
                results, _ = cleaner.clean_all()
                notify(results)
                ticker = 0
            elif not delayed_completed and ticker >= delayed_start_ticker:
                delayed_completed = True
                results, _ = cleaner.clean_all()
                notify(results)
                ticker = 0

            cleaner.monitor.waitForAbort(service_sleep)
            ticker += 1
        else:
            cleaner.monitor.waitForAbort(service_sleep)

    log("Abort requested. Terminating.")
    return
Esempio n. 17
0
def autostart():
    """
    Starts the cleaning service.
    """
    cleaner = Cleaner()

    service_sleep = 4  # Lower than 4 causes too much stress on resource limited systems such as RPi
    ticker = 0
    delayed_completed = False

    while not xbmc.abortRequested:
        if get_setting(service_enabled):
            scan_interval_ticker = get_setting(scan_interval) * 60 / service_sleep
            delayed_start_ticker = get_setting(delayed_start) * 60 / service_sleep

            if delayed_completed and ticker >= scan_interval_ticker:
                results = cleaner.clean_all()
                if results:
                    notify(results)
                ticker = 0
            elif not delayed_completed and ticker >= delayed_start_ticker:
                delayed_completed = True
                results = cleaner.clean_all()
                if results:
                    notify(results)
                ticker = 0

            xbmc.sleep(service_sleep * 1000)
            ticker += 1
        else:
            xbmc.sleep(service_sleep * 1000)

    print("Abort requested. Terminating.")
    return
Esempio n. 18
0
 def error(self, db, message=None, autoRestart=True):
     if message is None:
         message = '[Hour Boost - %s] დაფიქსირდა შეცდომა' % db.username
     if db.username in self.clients:
         print(
             colored('[Hour Boost] %s 🗙 Failed Hour Boost' % db.username,
                     'red'))
         del self.clients[db.username]
         db.errlog = exceptionTraceback()
         db.stopped = True
         db.finished = True
         db.save()
         user = User.objects.get(username=db.user)
         user.seen = False
         user.save()
         notify(user, message)
         # if user has remaining backup codes, automatically restart it
         if autoRestart and db.authcode != '' and db.authcode != None:
             print(
                 colored(
                     '[Hour Boost] %s Will Use Remaining Backup Code(s)' %
                     db.username, 'green'))
             db.stopped = False
             db.finished = False
             db.errlog = ''
             db.save()
         else:
             notify(
                 user,
                 '[Hour Boost - %s] შეიყვანეთ Backup კოდები' % db.username)
Esempio n. 19
0
 def update_alert(self, version):
     latest = Menu().check_version()
     if latest != version and latest != 0:
         notify('MusicBox Update is available', 1)
         time.sleep(0.5)
         notify('NetEase-MusicBox installed version:' + version +
                '\nNetEase-MusicBox latest version:' + latest, 0)
Esempio n. 20
0
 def open_camera_settings(self):
     settings_window = camerasettings.CameraSettingsWindow(
         self.camera.number)
     settings_window.doModal()
     del settings_window
     utils.notify(
         'Some changes may not take affect until the service is restarts.')
Esempio n. 21
0
def Playvid(url, name, download):
    videopage = utils.getHtml(url)
    videourl = re.compile('class="btn btn-1 btn-1e" href="([^"]+)" target="_blank"', re.DOTALL | re.IGNORECASE).findall(videopage)[0]
    if videourl:
        utils.playvid(videourl, name, download)
    else:
        utils.notify('Oh oh','Couldn\'t find a video')
Esempio n. 22
0
 def star_song(self):
     return_data = self.request_api(self.netease.fm_like,
                                    self.player.get_playing_id())
     if return_data != -1:
         notify("Added successfully!", 0)
     else:
         notify("Existing song!", 0)
Esempio n. 23
0
def Login():
    utils.log('================ VPNicity Login ================')
    with requests.Session() as s:
        try:
            s.get(LOGINURL)
        except: 
            return False
        
        USER     = ADDON.getSetting('USER')
        PASS     = ADDON.getSetting('PASS')
        PAYLOAD  = { 'log' : USER, 'pwd' : PASS, 'wp-submit' : 'Log In' }
        response = 'login_error'
        code     =  0

        if USER and PASS:
            login    = s.post(LOGINURL, data=PAYLOAD)
            response = login.content
            # code     = login.status_code
            # saveCookies(s.cookies, cookiefile)
        
        if 'no-access-redirect' in response:
            error   = '301 - No Access.'
            message = 'It appears that your subscription has expired.'
            utils.log(message + ' : ' + error)
            utils.dialogOK(message, error, 'Please check your account at www.vpnicity.com')

            KillVPN(silent=True)
            
            return False
            
        areLost    = 'Are you lost' in response
        loginError = 'login_error' in response
        okay       =  (not areLost) and (not loginError)
        
        if okay:
            message = 'Logged into VPNicity'
            utils.log(message)
            utils.notify(message)
            return True
            
        try:
            error = re.compile('<div id="login_error">(.+?)<br />').search(response).groups(1)[0]
            error = error.replace('<strong>',  '')
            error = error.replace('</strong>', '')
            error = error.replace('<a href="https://www.vpnicity.com/wp-login.php?action=lostpassword">Lost your password?</a>', '')
            error = error.strip()
            print error
        except:
            error = ''
            
        message = 'There was a problem logging into VPNicity'
        
        utils.log('************ VPNicity Error ************')
        utils.log(message + ' : ' + error)
        utils.log('****************************************')
        utils.dialogOK(message, error, 'Please check your account at www.vpnicity.com')
        
        KillVPN(silent=True)
        
    return False
 def toggle_preset(self):
     if self.preset_button.isSelected():
         self.camera.ptz_add_preset()
         utils.notify('Home Location is now Current Location')
     else:
         self.camera.ptz_delete_preset()
         utils.notify('Home Location is now Default Location')
Esempio n. 25
0
    def _populate_record(self, record, data):
        """
        Given mapping of data, copy values to attributes on record.

        Subclasses may override to provide schema validation, selective
        copy of names, and normalization of values if/as necessary.
        """
        changelog = []
        for key, value in data.items():
            if key.startswith('_'):
                continue  # invalid key
            if key == 'record_uid':
                self.record_uid = str(value)
                continue
            try:
                self._type_whitelist_validation(value)
            except ValueError:
                continue  # skip problem name!
            existing_value = getattr(self, key, None)
            if value != existing_value:
                changelog.append(key)
                setattr(record, key, value)
        if changelog:
            record._p_changed = True
            changelog = [
                Attributes(self.RECORD_INTERFACE, name) for name in changelog
            ]
            notify(ObjectModifiedEvent(record, *changelog))
Esempio n. 26
0
def add_show_intent_handler(handler_input):
    """ handler for Add Show Intent"""

    h = handler_input.request_envelope.context.system.user.access_token
    showtype = 'show'
    # If we are not auth, let the user know
    if h is None:
        reprompt = language.AUTH_ERROR
        handler_input.response_builder.speak(reprompt).ask(reprompt)
        return handler_input.response_builder.response
    headers = utils.build_headers(h, clientid)

    # get our persistent_attributes
    _perattr = handler_input.attributes_manager.persistent_attributes
    movie = get_slot_value(handler_input=handler_input, slot_name="showName")
    user_list = get_slot_value(handler_input=handler_input, slot_name="list_name")
    _list, _usecustomlist = utils.get_list(user_list, _perattr)
    # search for move and get the object
    b = trakt_api.search(movie, headers, showtype, False)
    if b['error']:
        # handle this
        handler_input.response_builder.speak(language.SHOW_404)
        return handler_input.response_builder.response

    y = b['show']
    # dig through our search and add the movie/show to our list or our Watchlist
    trakt_api.parse_search(b['type'], headers, y, _list, _usecustomlist, True)
    utils.notify(movie, b['type'], _list)
    handler_input.response_builder.speak(movie + " show has been added to your list " + str(_list))
    # .ask(reprompt)
    return handler_input.response_builder.response
Esempio n. 27
0
def PHVideo(url, name, download=None):
    progress.create('Play video', 'Searching videofile.')
    progress.update( 10, "", "Loading video page", "" )
    Supported_hosts = ['Openload.io', 'StreamCloud', 'NowVideo', 'FlashX', 'www.flashx.tv', 'streamcloud.eu', 'streamin.to']
    videopage = utils.getHtml(url, '')
    match = re.compile(r'<li id="link-([^"]+).*?xs-12">\s+Watch it on ([\w\.]+)', re.DOTALL | re.IGNORECASE).findall(videopage)
    if len(match) > 1:
        sites = []
        vidurls = []
        for videourl, site in match:
            if site in Supported_hosts:
                sites.append(site)
                vidurls.append(videourl)
        if len(sites) ==  1:
            sitename = match[0][1]
            siteurl = match[0][0]
        else:
            site = utils.dialog.select('Select video site', sites)
            sitename = sites[site]
            siteurl = vidurls[site]
    else:
        sitename = match[0][1]
        siteurl = match[0][0]
    outurl = "http://www.pornhive.tv/en/out/" + siteurl
    progress.update( 20, "", "Getting video page", "" )
    if 'loud' in sitename:
        progress.update( 30, "", "Getting StreamCloud", "" )
        playurl = getStreamCloud(outurl)
    elif "lash" in sitename:
        progress.update( 30, "", "Getting FlashX", "" )
        playurl = getFlashX(outurl)
    elif sitename == "NowVideo":
        progress.update( 30, "", "Getting NowVideo", "" )
        playurl = getNowVideo(outurl)        
    elif "Openload" in sitename:
        progress.update( 30, "", "Getting Openload", "" )
        progress.close()
        utils.PLAYVIDEO(outurl, name, download)
        return
    elif "streamin" in sitename:
        progress.update( 30, "", "Getting Streamin", "" )
        streaming = utils.getHtml(outurl, '')
        outurl=re.compile("action='([^']+)'").findall(streaming)[0]
        progress.close()
        utils.playvideo(outurl, name, download)
        return
    else:
        progress.close()
        utils.notify('Sorry','This host is not supported.')
        return
    progress.update( 90, "", "Playing video", "" )
    progress.close()
    if download == 1:
        utils.downloadVideo(playurl, name)
    else:
        iconimage = xbmc.getInfoImage("ListItem.Thumb")
        listitem = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
        listitem.setInfo('video', {'Title': name, 'Genre': 'P**n'})
        xbmc.Player().play(playurl, listitem)
Esempio n. 28
0
 def update_alert(self, version):
     latest = Menu().check_version()
     if latest != version and latest != 0:
         notify("MusicBox Update is available", 1)
         time.sleep(0.5)
         notify(
             "NetEase-MusicBox installed version:" + version +
             "\nNetEase-MusicBox latest version:" + latest, 0)
Esempio n. 29
0
def get_remote_hash(**kwargs):
    md5_hash = hashlib.md5()
    with urlopen(kwargs['url']) as request:
        for chunk in iter(lambda: request.read(4096), b''):
            md5_hash.update(chunk)
    md5 = str(md5_hash.hexdigest())
    if 'email' in kwargs.keys():
        notify(email=str(kwargs['email']), text=('File: ' + kwargs['url'] + ' | ' + 'MD5: ' + md5))
    return md5, kwargs['url']
def Favorites(fav, mode, name, url, img):
    if fav == "add":
        delFav(url)
        addFav(mode, name, url, img)
        utils.notify('Favorite added', 'Video added to the favorites')
    elif fav == "del":
        delFav(url)
        utils.notify('Favorite deleted', 'Video removed from the list')
        xbmc.executebuiltin('Container.Refresh')
Esempio n. 31
0
def Favorites(fav,mode,name,url,img):
    if fav == "add":
        delFav(url)
        addFav(mode, name, url, img)
        utils.notify('Favorite added','Video added to the favorites')
    elif fav == "del":
        delFav(url)
        utils.notify('Favorite deleted','Video removed from the list')
        xbmc.executebuiltin('Container.Refresh')
Esempio n. 32
0
 def open(cls, url='', language='en', post_data=None, get_data=None):
     if post_data is None:
         post_data = {}
     if get_data is not None:
         url += '?' + urlencode(get_data)
     logger.log.debug(url)
     result = True
     if len(post_data) > 0:
         cls.create_cookies(post_data)
     if cls._cookies is not None:
         req = urllib2.Request(url, cls._cookies)
         cls._cookies = None
     else:
         req = urllib2.Request(url)
     req.add_header('User-Agent', USER_AGENT)
     req.add_header('Content-Language', language)
     req.add_header("Accept-Encoding", "gzip")
     opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(
         cls.cookies))  # open cookie jar
     try:
         sleep(0.5)  # good spider
         response = opener.open(req)  # send cookies and open url
         cls.headers = response.headers
         # borrow from provider.py Steeve
         if response.headers.get("Content-Encoding", "") == "gzip":
             import zlib
             cls.content = zlib.decompressobj(16 +
                                              zlib.MAX_WBITS).decompress(
                                                  response.read())
         else:
             cls.content = response.read()
         response.close()
         cls.status = 200
         logger.log.debug("Status: " + str(cls.status))
         logger.log.debug(cls.content)
     except urllib2.HTTPError as e:
         cls.status = e.code
         logger.log.warning("Status: " + str(cls.status))
         result = False
         if e.code == 503:
             # trying to open with antibots tool
             sleep(0.5)  # good spider
             import cfscrape
             scraper = cfscrape.create_scraper(
             )  # returns a CloudflareScraper instance
             cls.content = scraper.get(url).content
             cls.status = 200
             notify("Antibot's  measure for %s" % url)
             logger.log.warning("Trying antibot's measure")
             result = True
     except urllib2.URLError as e:
         cls.status = e.reason
         logger.log.warning("Status: " + str(cls.status))
         if '[Errno 1]' in cls.status:
             notify('obsolete Kodi version to open %s' % url)
         result = False
     return result
Esempio n. 33
0
 def request_api(self, func, *args):
     result = func(*args)
     if result:
         return result
     if not self.login():
         print('you really need to login')
         notify("You need to log in")
         return False
     return func(*args)
Esempio n. 34
0
def add_movie_intent_handler(handler_input):
    """Handler for Add Movie Intent."""

    # get our persistent_attributes
    # if the user has launched the app greet them
    # set out session attributes
    _perattr = handler_input.attributes_manager.persistent_attributes
    attr = handler_input.attributes_manager.session_attributes
    if is_request_type("LaunchRequest")(handler_input):
        # _usecustomlist = _perattr['usecustomlist']
        attr["movie"] = {}
        attr["show"] = {}
        attr['readBoxOffice'] = False
        attr['readMovies'] = False
        attr['readShows'] = False
        attr['readBoth'] = False
        attr['active_request'] = ''
        attr['repeat'] = ''
        handler_input.response_builder.speak("Welcome To Radar the Trakt.tv tracker").ask("")
        return handler_input.response_builder.response

    # Get the value of the users auth token
    h = handler_input.request_envelope.context.system.user.access_token
    # _list = 'watchlist'
    _usecustomlist = False
    # If we are not auth, let the user know
    if h is None:
        handler_input.response_builder.speak(language.AUTH_ERROR)
        return handler_input.response_builder.response
    # Set all our headers for the trakt-api
    headers = utils.build_headers(h, clientid)
    print("Header= " + str(headers))
    # Get the movie name and throw it onto the movie var
    movie = get_slot_value(handler_input=handler_input, slot_name="movieName")
    use_list = get_slot_value(handler_input=handler_input, slot_name="list_name")
    # reprompt = "Are you sure you want to add "+movie+' to your list ?'
    # user gave us nothing lets do some checks to make sure we have saved attributes
    _list, _usecustomlist = utils.get_list(use_list, _perattr)
    # search for move and get the object
    b = trakt_api.search(movie, headers, "movie", True)
    if b['error']:
        # handle this
        handler_input.response_builder.speak("I couldn't find the show you requested")
        return handler_input.response_builder.response
    # force our movie/show object into a small var to make things easier
    y = b["movie"]
    # dig through our search and add the movie/show to our list or our Watchlist
    if trakt_api.parse_search(b['type'], headers, y, _list, _usecustomlist, True):
        # media_name, media_type, a_list
        utils.notify(movie, b['type'], _list)
        handler_input.response_builder.speak(movie + " has been added to your " + _list + " list")  # .ask(reprompt)
    else:
        # TODO Fix the notify to allow errors
        # utils.notify(movie, b['type'], _list)
        handler_input.response_builder.speak("There was a problem adding " + movie + " to your list " + _list)
    return handler_input.response_builder.response
Esempio n. 35
0
def Playvid(url, name, download):
    videopage = utils.getHtml(url)
    plurl = re.compile('\?u=([^"]+)"', re.DOTALL | re.IGNORECASE).findall(videopage)[0]
    plurl = 'http://sexix.net/qaqqew/playlist.php?u=' + plurl
    plpage = utils.getHtml(plurl, url)
    videourl = re.compile('file="([^"]+)"', re.DOTALL | re.IGNORECASE).findall(plpage)[0]
    if videourl:
        utils.playvid(videourl, name, download)
    else:
        utils.notify('Oh oh','Couldn\'t find a video')
Esempio n. 36
0
def notification_rev_msexperts(context, event):
    """
    To:     MSExperts
    When:   New answer from country
    """
    _temp = PageTemplateFile('question_answered_msexperts_msg.pt')
    if event.action in ['answer-to-lr']:
        observation = aq_parent(context)
        subject = u'New answer from country'
        notify(observation, _temp, subject, ROLE_MSE, 'question_answered')
Esempio n. 37
0
    def notify_playing(self):
        if not self.current_song:
            return

        if not self.config_notifier:
            return

        song = self.current_song
        notify("正在播放: {}\n{}-{}".format(song["song_name"], song["artist"],
                                        song["album_name"]))
Esempio n. 38
0
async def detect_key_hold(device_path, hold_time_sec=0.4):
    '''
    Asyncio coroutine task to detect trigger to start gesture detection

    '''
    try:
        base_reader = BaseReader(device_path)
        reader = Reader(base_reader)
        gesture_task = None
        area_patch = True

        area_x, area_y = 2850, 50

        state = {}
        async for event in reader:
            # borrowed from evdev's author's comment
            if event.type == ecodes.EV_KEY:
                # When the key is pressed, record its timestamp.
                if event.code == 330 and event.value == 1:
                    state[event.code] = event.timestamp(), event
                # When it's released, remove it from the state map.
                if event.value == 0 and event.code in state:
                    del state[event.code]
                    area_patch = True

            # Define a square patch of 200x200 around the top right corner
            # where the tap has to be detected
            if event.type == ecodes.EV_ABS:
                if event.code == 0:  # For ABS_X
                    if not event.value in range(area_x-100, area_x+100):
                        area_patch = False
                if event.code == 1:  # For ABS_Y
                    if not event.value in range(area_y-100, area_y+100):
                        area_patch = False
                # Check if any keys have been held
                # longer than hold_time_sec seconds.
            now = time.time()
            for code, ts_event in list(state.items()):
                timestamp, event = ts_event
                if (now - timestamp) >= hold_time_sec and area_patch:
                    del state[code]  # only trigger once
                    area_patch = True

                    if gesture_task is None:
                        notify("Tracking gestures...")
                        gesture_task = asyncio.create_task(
                            from_streams(base_reader))
                    else:
                        notify("Gesture tracking stopped")
                        gesture_task.cancel()
                        await gesture_task
                        gesture_task = None
    except  asyncio.CancelledError:
        reader.exit()
Esempio n. 39
0
def notification_mse(context, event):
    """
    To:     MSExperts
    When:   New question for your country
    """
    _temp = PageTemplateFile('answer_to_msexperts.pt')

    if event.action in ['phase1-assign-answerer', 'phase2-assign-answerer']:
        observation = aq_parent(context)
        subject = u'New question for your country'
        notify(observation, _temp, subject, 'MSExpert', 'answer_to_msexperts')
Esempio n. 40
0
def notification_se(context, event):
    """
    To:     SectorExpert
    When:   Redraft requested by LR.
    """
    _temp = PageTemplateFile('question_redraft.pt')

    if event.action in ['redraft']:
        observation = aq_parent(context)
        subject = u'Redraft requested.'
        notify(observation, _temp, subject, ROLE_SE, 'question_redraft')
Esempio n. 41
0
def notification_lr(context, event):
    """
    To:     LeadReviewer
    When:   New answer from country
    """
    _temp = PageTemplateFile('question_answered_lr_msg.pt')

    if event.action in ['answer-to-lr']:
        observation = aq_parent(context)
        subject = u'New answer from country'
        notify(observation, _temp, subject, ROLE_LR, 'question_answered')
Esempio n. 42
0
def test_syntax():
    data = get_current_config()
    test_result, message = check_config(data)

    if not test_result:
        utils.notify('Crontab config error', message, debug=True)

    crontab_exists = check_crontab_exists()

    if crontab_exists:
        remove_config()
def play():
    """ Main function to show all cameras """

    if settings.atLeastOneCamera():
        monitor.set_playingCamera("0")
        PlayerWindow = AllCameraDisplay()
        del PlayerWindow
        monitor.clear_playingCamera("0")

    else:
        utils.log(2, "No Cameras Configured")
        utils.notify("You must configure a camera first")
Esempio n. 44
0
def List():
    conn = sqlite3.connect(favoritesdb)
    c = conn.cursor()
    try:
        c.execute("SELECT * FROM favorites")
        for (name, url, mode, img) in c.fetchall():
            utils.addLink(name, url, int(mode), img, '', '', 'del')
        conn.close()
        xbmcplugin.endOfDirectory(utils.addon_handle)
    except:
        conn.close()
        utils.notify('No Favourites','No Favourites found')
        return
Esempio n. 45
0
    def fetchFile(self):
        retVal = self.FETCH_NOT_NEEDED
        fetch = False
        if not os.path.exists(self.filePath):  # always fetch if file doesn't exist!
            fetch = True
        else:
            interval = int(self.addon.getSetting('xmltv.interval'))
            if interval <> self.INTERVAL_ALWAYS:
                modTime = datetime.datetime.fromtimestamp(os.path.getmtime(self.filePath))
                td = datetime.datetime.now() - modTime
                # need to do it this way cause Android doesn't support .total_seconds() :(
                diff = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6) / 10 ** 6
                if ((interval == self.INTERVAL_12 and diff >= 43200) or
                        (interval == self.INTERVAL_24 and diff >= 86400) or
                        (interval == self.INTERVAL_48 and diff >= 172800)):
                    fetch = True
            else:
                fetch = True

        if fetch:

            username = utils.get_setting(addon_id,'username')
            password = utils.get_setting(addon_id,'password')
            base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
            tmpFile = os.path.join(self.basePath, 'tmp')
            f = open(tmpFile, 'wb')

            try:
                request = urllib2.Request(self.fileUrl)
		request.add_header("Authorization", "Basic %s" % base64string)   
                tmpData = urllib2.urlopen(request)
                data = tmpData.read()
                if tmpData.info().get('content-encoding') == 'gzip':
                    data = zlib.decompress(data, zlib.MAX_WBITS + 16)
                f.write(data)
                f.close()

            except urllib2.HTTPError, e:
		if e.code == 401:
                    utils.notify(addon_id, 'Authorization Error !!! Please Check Your Username and Password')
		else:
		    utils.notify(addon_id, e)
            
            if os.path.getsize(tmpFile) > 256:
                if os.path.exists(self.filePath):
                    os.remove(self.filePath)
                os.rename(tmpFile, self.filePath)
                retVal = self.FETCH_OK
                xbmc.log('[script.ivueguide] file %s was downloaded' % self.filePath, xbmc.LOGDEBUG)
            else:
                retVal = self.FETCH_ERROR
Esempio n. 46
0
 def add(self, record):
     """
     Add a record to container, append UUID to end of order; over-
     write existing entry if already exists for a UUID (in such case
     leave order as-is).
     """
     uid = str(record.record_uid)
     if not uid:
         raise ValueError('record has empty UUID')
     self._entries[uid] = record
     if uid not in self._order:
         self._order.append(uid)
         self._update_size()
     notify(ObjectAddedEvent(record, self, uid))
Esempio n. 47
0
 def run_checks(self, hook, files, check):
     result = 0
     for file_name in files:
         if self.file_is_candidate(file_name, check):
             utils.notify(
                 '{0}: {1}'.format(hook.capitalize(), check.output)
             )
             process = subprocess.Popen(
                 check.command.format(file_name.decode('utf-8')),
                 stdout=subprocess.PIPE,
                 stderr=subprocess.PIPE,
                 shell=True
             )
             out, err = process.communicate()
             if out or err:
                 output_lines = self.format_output(file_name, check, out)
                 utils.notify('\n'.join(output_lines))
                 if err:
                     utils.notify(err)
                 result = 1
         else:
             utils.notify(
                 'No candidates for check: {}. Skipping'.format(check.check)
             )
     return result
Esempio n. 48
0
def clean_database(showdialog=False):
    conn = sqlite3.connect(xbmc.translatePath("special://database/Textures13.db"))
    try:
        with conn:
            list = conn.execute("SELECT id, cachedurl FROM texture WHERE url LIKE '%%%s%%';" % ".systemcdn.net")
            for row in list:
                conn.execute("DELETE FROM sizes WHERE idtexture LIKE '%s';" % row[0])
                try: os.remove(xbmc.translatePath("special://thumbnails/" + row[1]))
                except: pass
            conn.execute("DELETE FROM texture WHERE url LIKE '%%%s%%';" % ".systemcdn.net")
            if showdialog:
                utils.notify('Finished','Cam4 images cleared')
    except:
        pass
Esempio n. 49
0
def Network():
    url     = 'http://www.iplocation.net/'
    request = requests.get(url)
    link    = request.content
    match   = re.compile("<td width='80'>(.+?)</td><td>(.+?)</td><td>(.+?)</td><td>.+?</td><td>(.+?)</td>").findall(link)
    count   = 1
    
    for ip, region, country, isp in match:
        if count <2:
            message = 'IP Address: %s Based in: %s ISP: %s' % (ip, country, isp)
            utils.notify(message)
            utils.log('VPNicity IP Address is: %s' % ip)
            utils.log('VPNicity Country is: %s' % country)
            count = count+1
Esempio n. 50
0
 def create(self, data=None):
     """
     Alternative factory for an IRecord object, does not store object.
     If data is not None, copy fields from data.
     """
     if data is None:
         data = {}
     uid = data.get('record_uid', str(uuid.uuid4()))  # get or random uuid
     record = self.factory(context=self, uid=uid)
     if data and (hasattr(data, 'get') and
                  hasattr(data, 'items')):
         self._before_populate(record, data)
         self._populate_record(record, data)
     notify(ObjectCreatedEvent(record))
     return record
Esempio n. 51
0
 def check_version(self):
     # 检查更新 && 签到
     try:
         mobilesignin = self.netease.daily_signin(0)
         if mobilesignin != -1 and mobilesignin['code'] != -2:
             notify("Mobile signin success", 1)
         time.sleep(0.5)
         pcsignin = self.netease.daily_signin(1)
         if pcsignin != -1 and pcsignin['code'] != -2:
             notify("PC signin success", 1)
         tree = ET.ElementTree(ET.fromstring(str(self.netease.get_version())))
         root = tree.getroot()
         return root[0][4][0][0].text
     except:
         return 0
Esempio n. 52
0
def main():
    parse_arguments()

    # Gets the Rhythmbox player from DBus
    bus = dbus.SessionBus()
    obj = bus.get_object("org.gnome.Rhythmbox", "/org/gnome/Rhythmbox/Player")
    player = dbus.Interface(obj, "org.gnome.Rhythmbox.Player")

    filename = sanitize(player.getPlayingUri())

    # Prompts user for confirmation on removing the file
    if confirm(filename, title="Delete this file?"):
        player.next()
        call(["rm", filename])
        notify("Removed", "\"" + filename + "\"", icon="user-trash-full")
Esempio n. 53
0
def HQPLAY(url, name, download=None):
    videopage = utils.getHtml(url, url)
    iframeurl = re.compile(r'<iframe\swidth="\d+"\sheight="\d+"\ssrc="([^"]+)"', re.DOTALL | re.IGNORECASE).findall(videopage)
    #if re.search('hqporner', iframeurl[0], re.DOTALL | re.IGNORECASE):
    #    videourl = getHQ(iframeurl[0])
    if re.search('bemywife', iframeurl[0], re.DOTALL | re.IGNORECASE):
        videourl = getBMW(iframeurl[0])
    elif re.search('5\.79', iframeurl[0], re.DOTALL | re.IGNORECASE):
        videourl = getIP(iframeurl[0])
    elif re.search('flyflv', iframeurl[0], re.DOTALL | re.IGNORECASE):
        videourl = getFly(iframeurl[0])
    else:
        utils.notify('Oh oh','Couldn\'t find a supported videohost')
        return
    utils.playvid(videourl, name, download)
Esempio n. 54
0
def VPN(label, abrv, server):
    if not validToRun():
        utils.log('Login Error via Context Menu')
        return False

    authPath = os.path.join(PROFILE, 'temp')
    cfgPath  = os.path.join(PROFILE, 'cfg.ovpn')

    KillVPN(silent=True)

    WriteAuthentication(authPath)
    WriteConfiguration(server, cfgPath, authPath)

    busy = utils.showBusy()

    response = OpenVPN(cfgPath)

    if busy:
        busy.close()

    success = True

    if response:
        label = label.rsplit(' (', 1)[0]
        if IsEnabled(response):
            # if utils.platform() == "android":
            #     xbmc.sleep(10000)
            message = '%s %s now enabled' % (label, TITLE)
            utils.notify(message)         
            xbmcgui.Window(10000).setProperty('VPNICITY_LABEL',  label)
            xbmcgui.Window(10000).setProperty('VPNICITY_ABRV',   abrv)
            xbmcgui.Window(10000).setProperty('VPNICITY_SERVER', server)
            ipcheck.Network()

        else:
            KillVPN(silent=True)
            if utils.platform() == "android":
                xbmc.sleep(5000)
            message = '%s %s failed to start. Please check your settings.' % (label, TITLE)
            utils.notify(message)
            ipcheck.Network() 
            success = False

    #DeleteFile(authPath)
    #DeleteFile(cfgPath)
    #DeleteFile(RESPONSE)

    return success
Esempio n. 55
0
def notification_ms(context, event):
    """
    To:     MSAuthority
    When:   Observation was finalised
    """
    _temp = PageTemplateFile('observation_finalised.pt')
    if event.action in ['phase1-close', 'phase2-confirm-finishing-observation']:
        observation = context
        subject = u'An observation for your country was finalised'
        notify(
            observation,
            _temp,
            subject,
            'MSAuthority',
            'observation_finalised'
        )
Esempio n. 56
0
 def songs_detail_new_api(self, music_ids, bit_rate=320000):
     action = 'http://music.163.com/weapi/song/enhance/player/url?csrf_token='  # NOQA
     self.session.cookies.load()
     csrf = ''
     for cookie in self.session.cookies:
         if cookie.name == '__csrf':
             csrf = cookie.value
     if csrf == '':
         notify('You Need Login', 1)
     action += csrf
     data = {'ids': music_ids, 'br': bit_rate, 'csrf_token': csrf}
     connection = self.session.post(action,
                                    data=encrypted_request(data),
                                    headers=self.header, )
     result = json.loads(connection.content)
     return result['data']
Esempio n. 57
0
def notification_rev_ph2(context, event):
    """
    To:     ReviewerPhase2
    When:   Observation finalised
    """
    _temp = PageTemplateFile('observation_finalised_rev_msg.pt')
    if event.action in ['phase2-confirm-finishing-observation']:
        observation = context
        subject = u'Your observation was finalised'
        notify(
            observation,
            _temp,
            subject,
            'ReviewerPhase2',
            'observation_finalised'
        )
Esempio n. 58
0
def List():
    if utils.addon.getSetting("chaturbate") == "true":
        cleanchat()
        cleancam4()
    conn = sqlite3.connect(favoritesdb)
    c = conn.cursor()
    try:
        c.execute("SELECT * FROM favorites")
        for (name, url, mode, img) in c.fetchall():
            utils.addDownLink(name, url, int(mode), img, '', '', 'del')
        conn.close()
        xbmcplugin.endOfDirectory(utils.addon_handle)
    except:
        conn.close()
        utils.notify('No Favorites','No Favorites found')
        return