Beispiel #1
0
 def _threadStatusCB(self, threadName, threadStatus):
     # check if the event corresponds to some of the
     # in-progress search threads
     recipient = self._threadsInProgress.get(threadName)
     if recipient:
         statusId = SEARCH_STATUS_PREFIX + recipient
         pyotherside.send(statusId, threadStatus)
Beispiel #2
0
 def update_all_shows_episodes(self, show_list = []):
     self.isUpdating = True
     pyotherside.send('updating', self.isUpdating)
     show_list = show_list or self.series_list
     async_worker = AsyncWorker(False)
     update_images_worker = AsyncWorker(True)
     i = 0
     n_shows = len(show_list)
     for i in range(n_shows):
         update_ended_shows = Settings().getConf(Settings.UPDATE_ENDED_SHOWS)
         show = show_list[i]
         if show.status and show.status == 'Ended' and not update_ended_shows:
             async_item = AsyncItem(self._empty_callback, (),
                                    self._set_show_episodes_complete_cb,
                                    (show, update_images_worker, i == n_shows - 1))
             async_worker.queue.put(async_item)
             continue
         pyotherside.send('episodesListUpdating', show.get_name())
         show.set_updating(True)
         async_item = AsyncItem(self.thetvdb.get_show_and_episodes,
                                (show.thetvdb_id, show.language,),
                                self._set_show_episodes_complete_cb,
                                (show, update_images_worker, i == n_shows - 1))
         async_worker.queue.put(async_item)
         async_item = AsyncItem(self._set_show_images,
                                (show,),
                                None,)
         update_images_worker.queue.put(async_item)
     async_worker.start()
     return async_worker
Beispiel #3
0
 def _search_finished_callback(self, tvdbshows, error):
     if not error:
         for show_id, show in tvdbshows:
             self._cached_tvdb_shows[show_id] = show
             self.search_results.append(show)
     self.searching = False
     pyotherside.send('searching', self.searching)
Beispiel #4
0
        def handle_data(self, data):

            if self.gotDate == 1:
                pyotherside.send('date_received', data)
                pass
            if self.counter2FirstEntrys > 14 and self.parseData == 1 and data != '\n' and data != '' and data != '\r' and self.endfile == 0:
                if self.counter == 0:
                    self.liste[0]["klasse"] = data
                    self.counter = self.counter + 1
                elif self.counter == 1:
                    self.liste[0]["stunde"] = data
                    self.counter = self.counter + 1
                elif self.counter == 2:
                    self.liste[0]["vertreter"] = data
                    self.counter = self.counter + 1
                elif self.counter == 3:
                    self.liste[0]["lehrer"] = data
                    self.counter = self.counter + 1
                elif self.counter == 4:
                    self.liste[0]["fach"] = data
                    self.counter = self.counter + 1
                elif self.counter == 5:
                    self.liste[0]["normRaum"] = data
                    self.counter = self.counter + 1
                elif self.counter == 6:
                    self.liste[0]["raum"] = data
                    self.counter = self.counter + 1
                elif self.counter == 7:
                    self.liste[0]["info"] = data
                    self.counter = self.counter + 1
                pass
            if self.parseData == 1:
                self.counter2FirstEntrys = self.counter2FirstEntrys + 1
Beispiel #5
0
 def reporthook(blocknum, blocksize, totalsize):
     readsofar = blocknum * blocksize
     if totalsize > 0:
         percent = (readsofar * 1e2 / totalsize) / 2.
         pyotherside.send("on-progress", percent)
     else:
         sys.stderr.write("read %d\n" % (readsofar,))
Beispiel #6
0
def cbNewItem(response):
    global eventCount
    eventCount += 1

    pyotherside.send('item-downloaded')

    bufferResponse(response)
Beispiel #7
0
def unistall(rpmname,version):
    p = subprocess.Popen("pkcon remove "+rpmname,shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    #0则安装成功
    retval = p.wait()
    print("removed,",rpmname)
    pyotherside.send("status","4",rpmname,version)
    return p.returncode
def download(url):
    '''Downloads specified file at specific url'''
    u = req.urlopen(url)
    if os.path.exists('retroarch_v1.0'):
        return False
    else:
        with open('retroarch.zip', 'wb') as f:
            meta = u.info()
            meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all
            meta_length = meta_func("Content-Length")
            file_size = None
            if meta_length:
                file_size = int(meta_length[0])

            file_size_dl = 0
            block_sz = 8192

            while True:
                buff = u.read(block_sz)
                if not buff:
                    break

                file_size_dl += len(buff)
                f.write(buff)

                status = ""
                if file_size:
                    status += "{0:6.2f}".format(file_size_dl * 100 / file_size)
                status += chr(13)
                pyotherside.send('download', status)


            print('RetroArch was successfully downloaded')
            return True
def exportBookmarkstoSailfishBrowser(bookmarks, sPath):
    bookmark_list = []

    home = os.environ['HOME']
    path = '/.local/share/'
    browser = 'org.sailfishos/sailfish-browser/'
    timestamp = str(datetime.datetime.now().timestamp())
    backup = sPath + '/bookmarks.json.bak' + timestamp

    try:
        bookmark_obj = json.loads(bookmarks)
        with open(home + path + browser + 'bookmarks.json', 'r') as f:
            exist_bookmarks = json.load(f)
        exist_urls = []
        for ebm in exist_bookmarks:
            bookmark_list.append(ebm)
            exist_urls.append(ebm['url'])

        for bm in bookmark_obj:
            if bm['url'] not in exist_urls:
                bookmark = {
                    'favicon': 'icon-launcher-bookmark',
                    'hasTouchIcon': False,
                    'title': bm['title'],
                    'url': bm['url']
                }
                bookmark_list.append(bookmark)

        os.renames(home + path + browser + 'bookmarks.json', backup)
        with open(home + path + browser + 'bookmarks.json', 'w') as f:
            json.dump(bookmark_list, f)
    except:
        pyotherside.send(traceback.print_exc())
Beispiel #10
0
 def online_status_updated(self, future):
     res = future.result()
     pyotherside.send(
         "set-conversation-online",
         self.conv.id_,
         dict(future.result())["presence_result"][0]["presence"]["available"],
     )
Beispiel #11
0
 def _mark_all_episodes(self, watched, season = None):
     episodes = self.get_episodes_by_season(season)
     for episode in episodes:
         if episode.already_aired():
             episode.watched = watched
     SeriesManager().updated()
     pyotherside.send('infoMarkupChanged')
Beispiel #12
0
 def set_watched(self, watched):
     if (self.watched == watched):
         return
     self.watched = watched
     pyotherside.send('watchedChanged', self.watched)
     pyotherside.send('infoMarkupChanged')
     SeriesManager().updated()
def getAuthorizationUrl():
    try:
        redirect_url = auth.get_authorization_url()
        return redirect_url
    except tweepy.TweepError:
        pyotherside.send("Error! Failed to get request token.")
        return ""
Beispiel #14
0
 def _update_tile(self, tilesource, zoom, display_zoom, scale_factor, tile,
                  timestamp):
     """Download missing tile and ask QML to render it."""
     key = tilesource.tile_key(tile)
     item = self.tilecollection.get(key)
     if item is not None:
         return pyotherside.send("show-tile", item.uid)
     path = tilesource.download(tile)
     if path is None: return
     uri = poor.util.path2uri(path) if os.path.isabs(path) else path
     corners = tilesource.tile_corners(tile)
     xmin, xmax, ymin, ymax = self._bbox
     # Abort if map moved so that tile is no longer in view.
     if xmax <= corners[2][0] or xmin >= corners[0][0]: return
     if ymax <= corners[2][1] or ymin >= corners[0][1]: return
     item = self.tilecollection.get_free(
         key, path, xmin, xmax, ymin, ymax, display_zoom, corners)
     pyotherside.send("render-tile", dict(display_zoom=display_zoom,
                                          nex=corners[0][0],
                                          nwx=corners[3][0],
                                          nwy=corners[3][1],
                                          scale=scale_factor*tilesource.scale,
                                          half_zoom=tilesource.half_zoom,
                                          smooth=tilesource.smooth,
                                          swy=corners[2][1],
                                          type=tilesource.type,
                                          uid=item.uid,
                                          uri=uri,
                                          z=tilesource.z,
                                          zoom=zoom))
Beispiel #15
0
 def set_title(self, future=None):
     title = get_conv_name(self.conv, show_unread=False,
                           truncate=True)
     pyotherside.send('set-conversation-title', self.conv.id_, title, get_unread_messages_count(self.conv),
                      self.status_message)
     if future:
         future.result()
Beispiel #16
0
    def _searchCB(self, searchId, results):
        """Handle address search results

        :param list results: address search results
        """
        # try to sort local search results by distance
        # TODO: make this configurable
        if searchId == "local":
            pos = self.gui.get("pos", None)
            if pos:
                distanceList = []
                for result in results:
                    distanceList.append((geo.distanceP2LL(result,pos[0], pos[1]), result))
                distanceList.sort()
                results = map(lambda x: x[1], distanceList)
        # covert the Points in the results to a list of dicts
        resultList = []
        for result in results:
            resultList.append(point2dict(result))

        resultId = SEARCH_RESULT_PREFIX + searchId
        pyotherside.send(resultId, resultList)
        thisThread = threading.currentThread()
        # remove the finished thread from tracking
        if thisThread.name in self._threadsInProgress:
            del self._threadsInProgress[thisThread.name]
Beispiel #17
0
 def _send_defaults(self):
     """Send default configuration to QML."""
     pyotherside.send("set-attribution", self.tilesource.attribution)
     pyotherside.send("set-auto-center", poor.conf.auto_center)
     pyotherside.send("set-gps-update-interval", poor.conf.gps_update_interval)
     pyotherside.send("set-center", *poor.conf.center)
     pyotherside.send("set-zoom-level", poor.conf.zoom)
Beispiel #18
0
def install(rpmpath):
    p = subprocess.Popen("pkcon -y install-local "+rpmpath,shell=True,stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    #0则安装成功
    retval = p.wait()
    print("installed,",rpmpath)
    pyotherside.send("2")
    return p.returncode
Beispiel #19
0
    def _notifyQMLCB(self, newTheme):
        """ Notify the QML context that the modRana theme changed

        :param newTheme: the new theme
        :type newTheme: dict
        """
        pyotherside.send("themeChanged", newTheme)
 def run(self):
     self.must_run = True
     while self.must_run:
         sleep(0.1)
         if get_presence_auth_user() is None:
             save_auth_user = load_presence_auth_user()
             logger.debug("No auth user set")
             if save_auth_user is not None:
                 logger.debug("Try to set the last one: "+ str(save_auth_user))
                 if save_auth_user in [i['name'] for i in load_presences()]:
                     set_presence_auth_user(save_auth_user)
                     # emit signal to select the auth user the auth_user list 
                     pyotherside.send('set_selected_auth_user', save_auth_user)
         # Process received sms queue
         if not recv_sms_q.empty():
             new_sms = recv_sms_q.get()
             status = self.sms_received(new_sms['phone_number'],
                           new_sms['message'])
             if status:
                 recv_sms_q.task_done()
         # Process sms to send queue
         if not send_sms_q.empty():
             new_sms = send_sms_q.get()
             self.send_sms(new_sms['to'],
                           new_sms['message'])
             send_sms_q.task_done()
     logger.debug("Scheduler stopped")
Beispiel #21
0
    def initialize(self, progname):
        assert self.core is None, 'Already initialized'

        self.core = core.Core(progname=progname)
        pyotherside.send('podcast-list-changed')

        self.core.config.add_observer(self._config_option_changed)
Beispiel #22
0
def paxel(url, name,output, blocks=8):
    size = GetUrlFileSize( url )
    ranges = SpliteBlocks( size, blocks )

    threadname = [ "thread_%d" % i for i in range(0, blocks) ]
    filename = [ "tmpfile_%d" % i for i in range(0, blocks) ]

    tasks = []
    for i in range(0,blocks):
        task = AxelPython( threadname[i], url, filename[i], ranges[i] )
        task.setDaemon( True )
        task.start()
        tasks.append( task )

    time.sleep(1)
    while islive(tasks):
        downloaded = sum( [task.downloaded for task in tasks] )
        process = downloaded/float(size)*100
        pyotherside.send("progress",name,process)
        time.sleep( 0.3 )

    filehandle = open( output, 'wb+' )
    for i in filename:
        f = open( i, 'rb' )
        filehandle.write( f.read() )
        f.close()
        try:
            os.remove(i)
            pass
        except:
            pass

    filehandle.close()
Beispiel #23
0
def get_posts(board_id,postno):

    board = basc_py4chan.Board(board_id)
    thread = board.get_thread(postno)

    post_list = []
    post_replies = {}

    if thread != None:
        all_posts = thread.all_posts



        for post in all_posts:

            post_values = {}

            post_values['no'] = post.post_id

            if post.post_id == postno :
                post_values['replies'] = len(thread.posts)
                post_values['sticky'] = int(thread.sticky)
            else:
                post_values['replies'] = 0
                post_values['sticky'] = 0

            post_values['closed'] = int(thread.closed)
            post_values['name'] = post.name
            post_values['time'] = post.timestamp
            post_values['ext'] = post.file_extension
            post_values['file_deleted'] = int(post.file_deleted)
            post_values['images'] = int(post.has_file)
            post_values['semantic_url'] = post.semantic_url
            post_values['thumbUrl'] = post.thumbnail_url
            post_values['imgUrl'] = post.file_url
            post_values['filename'] = post.filename
            post_values['has_file'] = int(post.has_file)

            if post.comment:
                replies = utils.collect_replies(post.comment)
                if replies:
                    for reply in replies:
                        if reply not in post_replies:
                            post_replies[reply]=[]
                        post_replies[reply].append(post.post_id)

            if post.subject and post.comment:
                post_values['com'] = '<b>{}</b><br>'.format(post.subject) + post.comment
            elif not post.subject and post.comment:
                post_values['com'] = post.comment
            elif post.subject and not post.comment:
                post_values['com'] = '<b>{}</b>'.format(post.subject)

            post_list.append(post_values)

        post_list  = utils.parse_posts(post_list,post_replies)
        pyotherside.send('posts', post_list)
    else:
        pyotherside.send('posts_status', post_list)
Beispiel #24
0
def start():
    # Authenticate and connect
    try:
        auth_with_token()
    except requests.exceptions.ConnectionError as e:
        error_title = e.args[0].args[0]
        error_description = e.args[0].args[1]
        pyotherside.send('show-network-error', "ConnectionError", error_title, str(error_description))
def saveImg(basename,volname):
    try:
        realpath=cachePath+basename+".png"
        isExis()
        shutil.copy(realpath,savePath+volname)
        pyotherside.send("status","1")
    except:
        pyotherside.send("status","-1")
Beispiel #26
0
def saveImg(md5name,savename):
    try:
        realpath=cachePath+md5name
        isExis()
        shutil.copy(realpath,savePath+savename+"."+findImgType(realpath))
        pyotherside.send("1")
    except:
        pyotherside.send("-1")
Beispiel #27
0
def saveImg(cachePath,savename):
    try:
        realpath=cachePath
        isExis()
        shutil.copy(realpath,savePath+savename+"."+findImgType(realpath))
        pyotherside.send("saved")
    except:
        pyotherside.send("error")
        pass
Beispiel #28
0
    def __load_data(self):
        url = 'https://gist.githubusercontent.com/blabber/babc4803141b0ec13fd613cc84eae074/raw'
        with open_request(url) as f:
            d = json.loads(f.read().decode('utf-8'))

        if d:
            if d['status'] == "error":
                raise JSendError(d['message'])
            pyotherside.send('dataLoaded', d)
    def load_config(self):
        if not os.path.exists(self.config_file):
            return

        with open(self.config_file, 'r') as f:
            c = json.load(f)

        if c:
            pyotherside.send('configLoaded', c)
Beispiel #30
0
 def modifyTimeout(self, timeoutId, newTimeout):
     """modify the duration of a timeout in progress"""
     with self.dataLock:
         if timeoutId in self.cronTab['timeout'].keys():
             # we don't store the timeout value Python-side,
             # so we just notify QML about the change
             pyotherside.send("modifyTimerTimeout", timeoutId, newTimeout)
         else:
             self.log.error("can't modify timeout, wrong id: %s", timeoutId)
Beispiel #31
0
 def search_shows(self, terms, language="en"):
     if not terms:
         return []
     self.search_results = []
     self.searching = True
     pyotherside.send('searching', self.searching)
     async_worker = AsyncWorker(True)
     async_item = AsyncItem(self.thetvdb.get_matching_shows, (
         terms,
         language,
     ), self._search_finished_callback)
     async_worker.queue.put(async_item)
     async_worker.start()
Beispiel #32
0
    def back(self, scroll_height):
        if len(self.history) == 1:
            return self.load(self.history[0], True)

        self.update_scroll_height(scroll_height)

        self.future.append(self.history.pop())
        page = self.top(self.history)

        if len(self.future) > 0:
            pyotherside.send('showForward')

        return self.load(page, True)
Beispiel #33
0
    def getDialogs(self):
        print("getDialogs function in Main.py")

        Dialoge = []
        try:
            ldb.connect()
        except:
            True
        AllDialogs = Dialogs.select()
        ldb.close()

        if not AllDialogs.exists():
            Dialoge.append({
                "name": "LOADING\nPLEASE WAIT",
                "chat_identification": "",
                "status": "",
                "timestamp": "",
                "data_dir": data_dir
            })
        else:
            for dialog in AllDialogs:
                user_status = dialog.status
                #UserStatusOffline(was_online=datetime.utcfromtimestamp(1525351401))
                if "UserStatusOnline" in user_status:  #Online
                    user_status = "green"
                    lastonlinetime = ""
                else:
                    if user_status == "UserStatusRecently()":  # Was online Recently
                        user_status = "orange"
                        lastonlinetime = ""
                    else:
                        print("User Status is " + str(user_status))
                        user_status = "red"
                        lastonlinetime = ""
                        if "UserStatusOffline" in dialog.status:
                            lastonlinetime = modules.BlueFunc.ElapsedTime(
                                dialog.status.split(
                                    "UserStatusOffline(was_online=datetime.utcfromtimestamp("
                                )[-1].replace("))", ""))

                Dialoge.append({
                    "name": dialog.name,
                    "chat_identification": dialog.identification,
                    "status": user_status,
                    "timestamp": lastonlinetime,
                    "data_dir": data_dir
                })

        #print("pyotherside.send(antwortGetDialogs, " + str(Dialoge) + ")")
        pyotherside.send("antwortGetDialogs", Dialoge)
Beispiel #34
0
    def GetArt(self, ID):
        print("antwortGetArt")
        self.busy2(True)
        Dict = libs.send.GetArt(str(ID))
        if len(Dict) == 0:
            os.system("test_vibrator")
        del Dict["identification"]

        Antwort = []
        for text, var in sorted(Dict.items()):
            print("text:" + str(text) + " var:" + str(var))
            Antwort.append({"name": str(text), "var" : str(var)})
        pyotherside.send("antwortGetArt", Antwort)
        self.busy2(False)
Beispiel #35
0
 def SearchArt(self, suche):
     self.busy(True)
     if not suche == "":
         Antwort = []
         IDList = libs.send.SearchArt({"suche": suche, "ort": "", "lieferant": ""})
         for ID in IDList:
             self.busy(True)
             Dict = libs.send.GetArt(str(ID))
             Antwort.append(Dict)
             self.busy(False)
         pyotherside.send("antwortSearchArt", Antwort) 
         if len(IDList) == 0:
             os.system("test_vibrator")
     self.busy(False)
Beispiel #36
0
def init():
    if not os.path.exists(CACHE_DIR):
        pyotherside.send("loginrequired")
        os.makedirs(CACHE_DIR)
        return

    if not os.path.exists(CACHE_FILE):
        pyotherside.send("loginrequired")
        return

    with open(CACHE_FILE, "r") as read_file:
        global account
        global robots
        global vendor
        robots = json.load(read_file)
        if (robots["vendor"] == "Neato"):
            vendor = Neato()
        elif (robots["vendor"] == "Vorwerk"):
            vendor = Vorwerk()

        account = Account(robots["token"], None, vendor)
        for r in robots["robots"]:
            pyotherside.send("rfound", r["name"])

        pyotherside.send("loginsuccessful")
Beispiel #37
0
def worker():
    while True:
        # pyotherside.send('download_worker')
        if not _queue.empty():
            # print('Get queue')
            # pyotherside.send('download_getqueue')
            url = _queue.get()
            # pyotherside.send('download_queueurl', url)
            download(url)
            pyotherside.send('downloaddone', url)
            _queue.task_done()
        else:
            # pyotherside.send('downloadsempty')
            time.sleep(2)
Beispiel #38
0
def addtimemark(filename, timemark):
    if os.path.exists(filename):
        if "/" in filename:
            filename = CACHEPATH + filename[filename.rfind("/"):] + ".timemark"
        else:
            filename = CACHEPATH + "/" + filename + ".timemark"
        timemark = timemark[9:]
        try:
            f = open(filename, "w")
            f.write(timemark)
            f.close()
        except Exception as e:
            pyotherside.send("error", "Can't create Timemark:\n" + e)
            print(e)
Beispiel #39
0
def get_threads(board_id):
    #threads = json.loads(req("https://a.4cdn.org/{board}/{page}.json".format(board=board, page=page)))

    board = basc_py4chan.Board(board_id)

    threads = []
    threads.extend(board.get_all_threads())

    thread_list = []

    for thread in threads:
        topic = thread.topic
        thread_values = {}
        thread_values['no'] = topic.post_number
        thread_values['board'] = board_id
        thread_values['post_board'] = board_id
        thread_values['replies'] = int(thread.num_replies)
        thread_values['sticky'] = int(thread.sticky)
        thread_values['closed'] = int(thread.closed)
        thread_values['name'] = topic.name
        thread_values['time'] = topic.timestamp
        thread_values['semantic_url'] = topic.semantic_url
        if thread.omitted_images:
            thread_values['images'] = thread.omitted_images
        else:
            thread_values['images'] = int(topic.has_file)

        thread_values['has_file'] = int(topic.has_file)

        if topic.has_file:
            thread_values['ext'] = topic.file_extension
            thread_values['file_deleted'] = int(topic.file_deleted)
            thread_values['thumbUrl'] = topic.thumbnail_url
            thread_values['thumbnail_url'] = topic.thumbnail_url
            thread_values['imgUrl'] = topic.file_url
            thread_values['file_url'] = topic.file_url
            thread_values['filename'] = topic.filename

        if topic.subject and topic.comment:
            thread_values['com'] = '<b>{}</b><br>'.format(
                topic.subject) + topic.comment
        elif not topic.subject and topic.comment:
            thread_values['com'] = topic.comment
        elif topic.subject and not topic.comment:
            thread_values['com'] = '<b>{}</b>'.format(topic.subject)

        thread_list.append(thread_values)

    thread_list = utils.parse_posts(thread_list)
    pyotherside.send('threads', thread_list)
Beispiel #40
0
 def on_message_sent(self, future, local_id=None):
     global loop, client
     try:
         pyotherside.send("remove-dummy-message", self.conv.id_, local_id)
         request = hangouts_pb2.SetFocusRequest(
             request_header=client.get_request_header(),
             conversation_id=hangouts_pb2.ConversationId(id=self.conv.id_),
             type=hangouts_pb2.FOCUS_TYPE_FOCUSED,
             timeout_secs=20,
         )
         asyncio.async(client.set_focus(request))
         print('Message sent successful')
     except hangups.NetworkError:
         print('Failed to send message')
Beispiel #41
0
 def run(self):
     if os.path.exists(glob.CACHEPATH + "/transmission"):
         shutil.rmtree(glob.CACHEPATH + "/transmission", ignore_errors=True)
     if os.path.exists(glob.CACHEPATH + "/config.cnf"):
         os.remove(glob.CACHEPATH + "/config.cnf")
     rez = [0, "txt"]
     sizeF = os.path.getsize(glob.SCRIPTPATH +
                             "/transmission_armv7l.tar.bz2") / (1024 * 16)
     i = 0
     in_file = open(glob.SCRIPTPATH + "/transmission_armv7l.tar.bz2", "rb")
     out_file = open(glob.DATAPATH + "/transmission.tar.bz2", "wb")
     data = in_file.read(1024 * 16)
     txt = "Copy transmission.tar.bz2"
     while data:
         out_file.write(data)
         i += 1
         rez = [i / sizeF * 100, txt]
         pyotherside.send('progressinstaller', rez)
         time.sleep(0.01)
         data = in_file.read(1024 * 16)
     out_file.close()
     in_file.close()
     rez = [rez[0], "Extract transmission"]
     pyotherside.send('progressinstaller', rez)
     time.sleep(0.01)
     tf = tarfile.open(glob.DATAPATH + "/transmission.tar.bz2")
     tf.extractall(glob.DATAPATH)
     tf.close()
     rez = [rez[0], "Cleaning"]
     pyotherside.send('progressinstaller', rez)
     time.sleep(0.01)
     os.remove(glob.DATAPATH + "/transmission.tar.bz2")
     rez = [100, "Success transmission install."]
     pyotherside.send('finishedinstaller', rez)
Beispiel #42
0
 def request_dialogs(self):
     dialogs_model = [
         {
             'name': 'Chat One',
             'entity_id': 'chat_1',
             'icon': ''
         },
         {
             'name': 'Chat Two',
             'entity_id': 'chat_2',
             'icon': ''
         },
     ]
     pyotherside.send('update_dialogs', dialogs_model)
Beispiel #43
0
def paddingSilence(inputPathPy, outputPathPy, tempAudioType, padHere,
                   positionSilence, durationSilence):
    sound = AudioSegment.from_file(inputPathPy)
    silence = AudioSegment.silent(duration=int(durationSilence))
    if ("beginning") in positionSilence:
        extract = silence + sound
    if ("end") in positionSilence:
        extract = sound + silence
    if ("cursor") in positionSilence:
        extract1 = sound[:int(padHere)]
        extract2 = sound[int(padHere):]
        extract = extract1 + silence + extract2
    extract.export(outputPathPy, format=tempAudioType)
    pyotherside.send('loadTempAudio', outputPathPy)
Beispiel #44
0
 def _set_show_images(self, show):
     thetvdb_id = show.thetvdb_id
     if thetvdb_id == -1:
         return
     self._assign_existing_images_to_show(show)
     seasons = show.get_seasons()
     for key, image in list(show.season_images.items()):
         if not os.path.isfile(image):
             del show.season_images[key]
             self.changed = True
     # Check if the download is needed
     if len(seasons) == len(show.season_images.keys()) and \
        show.image and os.path.isfile(show.image):
         pyotherside.send('showArtChanged')
         return
     image_choices = self.thetvdb.get_show_image_choices(thetvdb_id)
     for image in image_choices:
         image_type = image[1]
         url = image[0]
         if image_type  == 'poster' and \
            (not show.image or not os.path.isfile(show.image)):
             show.downloading_show_image = True
             pyotherside.send('showArtChanged')
             target_file = os.path.join(DATA_DIR, show.get_poster_prefix())
             image_file = os.path.abspath(image_downloader(
                 url, target_file))
             show.set_cover_image(image_file)
             show.downloading_show_image = False
             self.changed = True
             pyotherside.send('showArtChanged')
         elif image_type == 'season':
             season = image[3]
             if season in seasons and \
                season not in show.season_images.keys():
                 show.downloading_season_image = True
                 pyotherside.send('showArtChanged')
                 target_file = os.path.join(
                     DATA_DIR, show.get_season_poster_prefix(season))
                 try:
                     image_file = os.path.abspath(
                         image_downloader(url, target_file))
                 except Exception as exception:
                     logging.debug(str(exception))
                 else:
                     show.season_images[season] = image_file
                 show.downloading_season_image = False
                 self.changed = True
                 pyotherside.send('showArtChanged')
         if show.image and len(show.season_images) == len(seasons):
             break
Beispiel #45
0
 def update_typing(self):
     global user_list
     typers = [self.conv.get_user(user_id).first_name
               for user_id, status in self.typing_statuses.items()
               if status == hangouts_pb2.TYPING_TYPE_STARTED and user_id != user_list._self_user.id_]
     if len(typers) > 0:
         typing_message = '{} {} typing...'.format(
             ', '.join(sorted(typers)),
             'is' if len(typers) == 1 else 'are'
         )
     else:
         typing_message = ''
     if self.status_message != typing_message:
         self.status_message = typing_message
         pyotherside.send('set-conversation-status', self.conv.id_, typing_message, sorted(typers))
Beispiel #46
0
def show_stat():
    uevent = open('/sys/class/power_supply/battery/uevent').read()
    for line in uevent.split('\n'):
        if line == '':
            continue
        i = line.split('=')
        battery[i[0]] = i[1]
    if '-' in battery['POWER_SUPPLY_CURRENT_NOW']:
        battery['POWER_SUPPLY_CURRENT_NOW'] = int(
            int(battery['POWER_SUPPLY_CURRENT_NOW'][1:]) / 1000)
    else:
        battery['POWER_SUPPLY_CURRENT_NOW'] = int(
            int('-{}'.format(battery['POWER_SUPPLY_CURRENT_NOW'])) / 1000)
    print('send: stat')
    pyotherside.send('stat', battery)
Beispiel #47
0
def createWaveformImage(inputPathPy, outputWaveformPath, waveformColor,
                        waveformPixelLength, waveformPixelHeight, stretch):
    waveformPixelLength = str(int(waveformPixelLength))
    waveformPixelHeight = str(int(waveformPixelHeight))
    #subprocess.run([ "/usr/share/harbour-audiocut/lib/ffmpeg/ffmpeg_static", "-y", "-i", "/"+inputPathPy, "-filter_complex", stretch+"showwavespic=s="+waveformPixelLength+"x"+waveformPixelHeight+":colors="+waveformColor, "-frames:v", "1", "/"+outputWaveformPath, "-hide_banner" ])
    subprocess.run([
        "/usr/bin/ffmpeg", "-y", "-i", "/" + inputPathPy, "-filter_complex",
        stretch + "showwavespic=s=" + waveformPixelLength + "x" +
        waveformPixelHeight + ":colors=" + waveformColor, "-frames:v", "1",
        "/" + outputWaveformPath, "-hide_banner"
    ])
    sound = AudioSegment.from_file(inputPathPy)
    audioLengthMilliseconds = len(sound)
    pyotherside.send('loadImageWaveform', outputWaveformPath,
                     audioLengthMilliseconds)
Beispiel #48
0
 def set_basemap(self, basemap):
     """Set basemap from string `basemap`."""
     try:
         newmap = (self.basemap is None or basemap != self.basemap.id)
         self.basemap = poor.Map(basemap)
         poor.conf.set_basemap(basemap)
         if newmap: pyotherside.send('basemap.changed')
     except Exception as error:
         print("Failed to load basemap '{}': {}"
               .format(basemap, str(error)),
               file=sys.stderr)
         if self.basemap is None:
             default = poor.conf.get_default("basemap")
             if default != basemap:
                 self.set_basemap(default)
Beispiel #49
0
    def _dispatchNotificationCB(self, text, msTimeout=5000, icon=""):
        """Let the QML context know that it should show a notification

        :param str text: text of the notification message
        :param int msTimeout: how long to show the notification in ms
        """

        self.log.debug("notify:\n message: %s, timeout: %d" %
                       (text, msTimeout))
        pyotherside.send(
            "pythonNotify",
            {
                "message": newlines2brs(text),  # QML uses <br> in place of \n
                "timeout": msTimeout
            })
Beispiel #50
0
def volumeFadeIn(inputPathPy, outputPathPy, tempAudioType, fromPosMillisecond,
                 toPosMillisecond):
    sound = AudioSegment.from_file(inputPathPy)
    extract1 = sound[:int(fromPosMillisecond)]
    extract3 = sound[int(toPosMillisecond):]
    extract2 = sound[int(fromPosMillisecond):int(toPosMillisecond)]
    if len(extract2) > 0:
        middle = extract2.fade(from_gain=-120.0,
                               start=0,
                               duration=len(extract2))
        extract = extract1 + middle + extract3
    else:
        extract = extract1 + extract3
    extract.export(outputPathPy, format=tempAudioType)
    pyotherside.send('loadTempAudio', outputPathPy)
Beispiel #51
0
    def _searchCB(self, searchId, results):
        """Handle address search results

        :param list results: address search results
        """
        resultList = []
        for result in results:
            resultList.append(point2dict(result))

        resultId = SEARCH_RESULT_PREFIX + searchId
        pyotherside.send(resultId, resultList)
        thisThread = threading.currentThread()
        # remove the finished thread from tracking
        if thisThread.name in self._threadsInProgress:
            del self._threadsInProgress[thisThread.name]
Beispiel #52
0
def start_seren():
    """ Run Seren without ncurses and connect pipes """
    username = getpass.getuser()
    seren = subprocess.Popen(
        shlex.split('seren -N'),
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
    )
    global stdin
    stdin = seren.stdin
    pyotherside.atexit(lambda: kill(seren))
    _thread.start_new_thread(read_output, (seren.stdout, ))
    pyotherside.send('node-join', datetime.datetime.now(),
                     html.escape(username), '127.0.0.1:8110')
Beispiel #53
0
def addignore(dt=""):
    global IGNORE
    if not (dt in IGNORE):
        IGNORE.append(dt)
        try:
            f = open(TMPBUF, "w")
            tmp = ""
            for da in IGNORE:
                tmp += da + "\n"
            f.write(tmp)
            f.close()
            removetimemark(dt)
        except Exception as e:
            pyotherside.send("error", "Can't create cache file:\n" + TMPBUF)
            print(e)
Beispiel #54
0
    def GetLieferscheine(self, identification, kunde, fertige, eigene):
        print("Lieferscheine")
        Dict = {}
        Dict["identification"] = str(identification)
        Dict["kunde_id"] = str(kunde)
        Dict["fertig"] = bool(fertige)
        Dict["eigene"] = bool(eigene)

        listeDerElemente = libs.send.SearchLieferschein(Dict)

        Antwort = []
        for item in listeDerElemente:
            DATA = libs.send.GetLieferschein(str(item))
            Antwort.append(DATA)
        pyotherside.send("antwortSearchLieferscheine", Antwort)
Beispiel #55
0
    def request_messages(self, entity_id, last_id=0, count=20):
        entity = self.get_entity(int(entity_id))
        last_id = int(last_id)

        if not last_id:
            # initial loading
            # check for older messages (if less than <count> cached)
            if database.messages_count(entity_id) < count:
                first_message_id = database.get_first_message(entity_id)
                self.download_messages(entity,
                                       limit=count,
                                       offset_id=first_message_id)

            # check for newer messages than chached
            # get last message from database
            last_message_id = database.get_last_message(entity_id)
            if not last_message_id:
                # nothing cached yet
                self.download_messages(entity, limit=count, min_id=last_id)
            else:
                # load everything missing
                self.download_messages(entity,
                                       limit=0,
                                       min_id=last_message_id + 1)

            # collect latest messages from cache
            messages = database.get_message_history(entity_id, limit=count)

        else:
            # load older messages
            # check oldest messages in cache
            first_message_id = database.get_first_message(entity_id)

            # load even older messages from server
            if first_message_id >= last_id:
                self.download_messages(entity,
                                       limit=count,
                                       offset_id=first_message_id)

            # collect requested messages from cache
            messages = database.get_message_history(entity_id,
                                                    limit=count,
                                                    max_id=last_id - 1)

        messages_model = [
            self.build_message_dict(msg, sender) for msg, sender in messages
        ]
        pyotherside.send('new_messages', entity_id, messages_model)
Beispiel #56
0
 def _load_more(self):
     if not self.loading and not self.first_loaded:
         self.loading = True
         try:
             conv_events = yield from self.conv.get_events(
                 self.conv.events[0].id_)
             for conv_event in reversed(conv_events):
                 if (isinstance(conv_event, hangups.ChatMessageEvent)):
                     user = self.conv.get_user(conv_event.user_id)
                     self.handle_message(conv_event, user, False, "top")
         except (IndexError, hangups.NetworkError):
             conv_events = []
         if len(conv_events) == 0:
             self.first_loaded = True
             pyotherside.send('on-first-message-loaded', self.conv.id_)
         self.loading = False
Beispiel #57
0
def slow_function(path=glob.CACHEPATH):
    global BGTHREAD
    pauseTorrentLoad()
    settingsLoad()
    for filename in os.listdir(path):
        if filename.find(".torrent") > -1:
            sootv = False
            adr = os.path.join(glob.CACHEPATH, filename)
            for i in range(0, len(BGTHREAD)):
                if BGTHREAD[i] != None:
                    if BGTHREAD[i].FILENAME == adr:
                        sootv = True
                        break
            if sootv == False:
                transmission_create(adr)
    pyotherside.send('finished')
Beispiel #58
0
    def searchListFileService(self, count, param):
        '''
            count: int pageSzie

            param: str query 

            return: list
        '''
        results = self.service.files().list(
            pageSize=int(count), q=param,
            fields=self.service_search_fields).execute()
        items = results.get('files', [])
        print('testFunction::resultsParse::items')
        pyotherside.send('iconParseSetting', self.configBooleanIconCheck())
        pyotherside.send('setIcon', str(self.configParser('iconSet')))
        return items
Beispiel #59
0
 def get_sender(self, sender_id):
     if sender_id == 'self':
         if not self.user:
             self.user = database.get_self()
         if not self.user:
             inputuser = tl.types.InputUserSelf()
             r = self.invoke(
                 tl.functions.users.GetUsersRequest((inputuser, )))
             self.user = r[0]
             database.add_sender(self.user)
             database.set_meta(self_id=self.user.id)
         return self.user
     sender = database.get_sender(sender_id)
     if not sender:
         pyotherside.send('log', 'Sender {} not found'.format(sender_id))
     return sender
Beispiel #60
0
 def reconnect(self, new_dc=None):
     try:
         self.client.reconnect(new_dc)
         self.connected = True
     except OSError:
         return False
     pyotherside.send('connection', True)
     if not self.client._update_handlers:
         self.client.add_update_handler(self.update_handler)
     try:
         self.client._set_updates_thread(running=True)
     except RuntimeError:
         # still running
         pass
     self.get_updates()
     return True