Ejemplo n.º 1
0
    def on_read_data(self):
        if self.receivers(self.finished) == 0:
            self.finished.connect(lambda reply: self.on_finished())
        self.connect_timer.stop()
        data = self.reply.readAll()
        self.current_event_string += bytes(data).decode('utf8')
        if len(self.current_event_string
               ) > 0 and self.current_event_string[-2:] == '\n\n':
            for event in self.current_event_string.split('\n\n'):
                if len(event) == 0:
                    continue
                event = event[5:] if event.startswith('data:') else event
                json_dict = json.loads(event)

                received_events.insert(0, (json_dict, time.time()))
                if len(received_events
                       ) > 100:  # Only buffer the last 100 events
                    received_events.pop()

                event_type, event = json_dict.get("type"), json_dict.get(
                    "event")
                reaction = self.reactions_dict.get(event_type)
                if reaction:
                    if event:
                        reaction(event)
                    else:
                        reaction()
                elif event_type == NTFY.TRIBLER_EXCEPTION.value:
                    raise RuntimeError(json_dict["event"]["text"])
            self.current_event_string = ""
Ejemplo n.º 2
0
    def on_received_metainfo(self, response):
        if not response or not self or self.closed:
            return

        if 'error' in response:
            if response['error'] == 'metainfo error':
                # If it failed to load metainfo for max number of times, show an error message in red.
                if self.metainfo_retries > METAINFO_MAX_RETRIES:
                    self.dialog_widget.loading_files_label.setStyleSheet(
                        "color:#ff0000;")
                    self.dialog_widget.loading_files_label.setText(
                        "Failed to load files. Click to retry again.")
                    return
                self.perform_files_request()

            elif 'code' in response['error'] and response['error'][
                    'code'] == 'IOError':
                self.dialog_widget.loading_files_label.setText(
                    "Unable to read torrent file data")
            else:
                self.dialog_widget.loading_files_label.setText(
                    f"Error: {response['error']}")
            return

        metainfo = json.loads(unhexlify(response['metainfo']))
        if 'files' in metainfo['info']:  # Multi-file torrent
            files = metainfo['info']['files']
        else:
            files = [{
                'path': [metainfo['info']['name']],
                'length': metainfo['info']['length']
            }]

        # Show if the torrent already exists in the downloads
        if response.get('download_exists'):
            self.dialog_widget.existing_download_info_label.setText(
                "Note: this torrent already exists in the Downloads")
        else:
            self.dialog_widget.existing_download_info_label.setText("")

        self.dialog_widget.files_list_view.clear()
        for filename in files:
            item = DownloadFileTreeWidgetItem(
                self.dialog_widget.files_list_view)
            item.setText(0, '/'.join(filename['path']))
            item.setText(1, format_size(float(filename['length'])))
            item.setData(0, Qt.UserRole, filename)
            item.setCheckState(2, Qt.Checked)
            self.dialog_widget.files_list_view.addTopLevelItem(item)

        self.has_metainfo = True
        self.dialog_widget.loading_files_label.setHidden(True)
        self.dialog_widget.download_files_container.setHidden(False)
        self.dialog_widget.files_list_view.setHidden(False)
        self.dialog_widget.adjustSize()
        self.on_main_window_resize()

        self.received_metainfo.emit(metainfo)
Ejemplo n.º 3
0
    async def get_channel_description(self, request):
        channel_pk, channel_id = self.get_channel_from_request(request)
        with db_session:
            channel_description = self.session.mds.ChannelDescription.select(
                lambda g: g.public_key == channel_pk and g.origin_id == channel_id
            ).first()

        response_dict = loads(channel_description.json_text) if (channel_description is not None) else {}
        return RESTResponse(response_dict)
Ejemplo n.º 4
0
 def __init__(self, file_path):
     """
     :param file_path: path to version_history.json file. Will be loaded if exists, or created anew if does not.
     """
     self.file_path = file_path
     self.version_history = json.loads(
         file_path.read_text().strip()) if file_path.exists() else {
             "last_version": None,
             "history": {}
         }
Ejemplo n.º 5
0
async def test_get_channel_description(enable_chant, enable_api, session):
    """
    Test getting description of the channel from the database
    """
    descr_txt = "foobar"
    with db_session:
        chan = session.mds.ChannelMetadata.create_channel(title="bla")
        channel_description = session.mds.ChannelDescription(
            origin_id=chan.id_,
            json_text=dumps({"description_text": descr_txt}))
    response_dict = await do_request(
        session,
        f'channels/{hexlify(chan.public_key)}/{chan.id_}/description',
        expected_code=200)
    assert response_dict == loads(channel_description.json_text)
Ejemplo n.º 6
0
 async def put_channel_description(self, request):
     channel_pk, channel_id = self.get_channel_from_request(request)
     request_parsed = await request.json()
     updated_json_text = dumps({"description_text": request_parsed["description_text"]})
     with db_session:
         channel_description = self.session.mds.ChannelDescription.select(
             lambda g: g.public_key == channel_pk and g.origin_id == channel_id
         ).first()
         if channel_description is not None:
             channel_description.update_properties({"json_text": updated_json_text})
         else:
             channel_description = self.session.mds.ChannelDescription(
                 public_key=channel_pk, origin_id=channel_id, json_text=updated_json_text, status=NEW
             )
     return RESTResponse(loads(channel_description.json_text))
Ejemplo n.º 7
0
    def load(self, file_path: Path):
        self.file_data = json.loads(file_path.read_text().strip())
        if "history" not in self.file_data:
            raise VersionError("Invalid history file structure")

        # timestamps needs to be converted to float before sorting
        history_items = [
            (float(time_str), version_str)
            for time_str, version_str in self.file_data["history"].items()
        ]
        for timestamp, version_str in sorted(history_items):
            version = TriblerVersion(self.root_state_dir, version_str,
                                     timestamp)
            # store only versions with directories:
            if version.state_exists():
                # eventually store only the latest launched version with the same major_minor tuple
                self.add_version(version)