Ejemplo n.º 1
0
    def delete_geojson_and_information(layers):
        """Save project basic information.

        :param layers: vector layer that will be checked
        :type layers: [QgsVectorLayer]
        """
        for layer in layers:
            qgis_layer = QgsMapLayerRegistry.instance().mapLayer(layer)
            organization_slug, project_slug, type = \
                Utilities.get_organization_project_slug(qgis_layer)
            project_folder = get_path_data(
                organization_slug=organization_slug,
                project_slug=project_slug)
            project_path = os.path.join(
                project_folder,
                '%s.geojson' % type
            )
            os.remove(project_path)

            # check geojson is not present
            geojson_present = False
            for fname in os.listdir(project_folder):
                if fname.endswith('.geojson'):
                    geojson_present = True
                    break
            if not geojson_present:
                try:
                    shutil.rmtree(project_folder)
                except OSError:
                    pass
Ejemplo n.º 2
0
    def get_basic_information(organization_slug, project_slug):
        """Get basic information that already saved.

        :param organization_slug: organization slug for data
        :type organization_slug: str

        :param project_slug: project_slug for data
        :type project_slug: str

        :return: information
        :rtype: dict
        """
        filename = get_path_data(
            organization_slug=organization_slug,
            project_slug=project_slug)
        filename = os.path.join(
            filename,
            'information.json'
        )
        if not os.path.isfile(filename):
            return {}

        try:
            file_ = open(filename, 'r')
            information = file_.read()
            file_.close()
            return json.loads(information)
        except TypeError:
            return {}
Ejemplo n.º 3
0
    def all_data(self):
        """Return all data from this step.

        :returns: step 1 data
        :rtype: dict
        """
        data = dict()
        data['organisation'] = self.selected_organisation()
        data['project_name'] = self.project_name()
        data['project_url'] = self.project_url()
        data['description'] = self.project_description_text.toPlainText()
        data['private'] = self.is_project_private.isChecked()

        # Get contacts
        data['contacts'] = []
        contact_item_list = self.project_contact_list.selectedItems()
        for contact_item in contact_item_list:
            contact = contact_item.data(Qt.UserRole)
            contact_data = {}
            if contact.name:
                contact_data['name'] = contact.name
            if contact.phone:
                contact_data['tel'] = contact.phone
            if contact.email:
                contact_data['email'] = contact.email
            data['contacts'].append(contact_data)

        # Get extent
        layer = self.selected_layer()
        if self.use_layer_extents.isChecked():
            # Layer extent
            extent = layer.extent()
        else:
            # Canvas extent
            extent = self.parent.iface.mapCanvas().extent()

        geometry = QgsGeometry().fromRect(extent)
        data['extent'] = geometry.exportToGeoJSON()

        # Save layer to geojson format
        output_file = get_path_data(project_slug='temp_project')
        output_file = os.path.join(output_file, '%s.geojson' % 'temp_project')

        result = QgsVectorFileWriter.writeAsVectorFormat(
            layer, output_file, 'utf-8', layer.crs(), 'GeoJson')

        if result == QgsVectorFileWriter.NoError:
            LOGGER.debug('Wrote layer to geojson: %s' % output_file)
            with open(output_file) as json_data:
                layer_data = json.load(json_data)
                data['locations'] = layer_data
            os.remove(output_file)
        else:
            LOGGER.error('Failed with error: %s' % result)
        return data
Ejemplo n.º 4
0
    def get_downloaded_projects(organization):
        """Get downloaded projects based on organization

        :return: downloaded projects
        :rtype: list of dict
        """
        file_path = get_path_data(organization)

        list_files = []

        for dirpath, _, filenames in os.walk(file_path):
            for f in filenames:
                if 'geojson' in f:
                    if Utilities.is_windows():
                        splitter = '\\'
                    else:
                        splitter = '/'
                    abs_path = os.path.abspath(
                        os.path.join(dirpath, f)).split('.')[1].split(
                        splitter)
                    names = []

                    try:
                        project_name = abs_path[-2].decode('utf-8')
                    except (UnicodeDecodeError, UnicodeEncodeError):
                        project_name = unicode(abs_path[-2])

                    normalized = unicodedata.normalize(
                                    'NFKC',
                                    project_name)

                    names.append(abs_path[-3])
                    names.append(normalized)
                    names.append(abs_path[-1])

                    list_files.append(
                        '/'.join(names)
                    )
        projects = []

        for layer in QgsMapLayerRegistry.instance().mapLayers().values():
            if layer.name() in list_files:
                information = \
                    Utilities.get_basic_information_by_vector(layer)

                projects.append({
                    'id': layer.id(),
                    'name': layer.name(),
                    'information': information,
                    'vector_layer': layer
                })

        return projects
Ejemplo n.º 5
0
    def get_all_downloaded_projects():
        """Get all downloaded projects

        :return: downloaded projects
        :rtype: list of dict
        """
        file_path = get_path_data()

        projects = []
        organizations = next(os.walk(file_path))[1]

        for organization in organizations:
            projects.extend(Utilities.get_downloaded_projects(organization))

        return projects
Ejemplo n.º 6
0
    def save_layer(geojson, organization_slug, project_slug):
        """Save geojson to local file.

        :param organization_slug: organization slug for data
        :type organization_slug: str

        :param project_slug: project_slug for getting spatial
        :type project_slug: str

        :param geojson: geojson that will be saved
        :type geojson: JSON object

        :return: layers
        :rtype: [QgsVectorLayer]
        """
        geojson = GeojsonParser(geojson)
        filename = get_path_data(
            organization_slug=organization_slug,
            project_slug=project_slug)

        if not os.path.exists(filename):
            os.makedirs(filename)

        layers = geojson.get_geojson_for_qgis()
        vlayers = []
        for key, value in layers.iteritems():
            geojson_name = os.path.join(
                filename,
                '%s.geojson' % key
            )
            file_ = open(geojson_name, 'w')
            file_.write(json.dumps(value, sort_keys=True))
            file_.close()
            vlayer = QgsVectorLayer(
                geojson_name, "%s/%s/%s" % (
                    organization_slug, project_slug, key
                ),
                "ogr"
            )
            QgsMapLayerRegistry.instance().addMapLayer(vlayer)
            vlayers.append(vlayer)
        return vlayers
Ejemplo n.º 7
0
    def save_project_basic_information(
            information,
            vlayers=None,
            relationship_layer_id=None,
            party_layer_id=None):
        """Save project basic information.

        :param information: basic information that will be saved
        :type information: dict

        :param vlayers: list of Spatial vector layers
        :type vlayers: list of QgsVectorLayer

        :param relationship_layer_id: Id for relationship layer
        :type relationship_layer_id: str

        :param party_layer_id: Id for party layer
        :type party_layer_id: str
        """
        organization_slug = information['organization']['slug']
        project_slug = information['slug']

        # Save new contacts to db
        if 'contacts' in information:
            project_contacts = information['contacts']

            for contact in project_contacts:

                phone = None
                email = None

                try:
                    phone = contact['tel']
                except KeyError:
                    pass

                try:
                    email = contact['email']
                except KeyError:
                    pass

                contact_from_db = Contact.get_rows(
                    name=contact['name'],
                    phone=phone,
                    email=email
                )

                if not contact_from_db:
                    new_contact = Contact()
                    new_contact.name = contact['name']
                    new_contact.email = contact['email']
                    new_contact.phone = contact['tel']
                    new_contact.save()

        filename = get_path_data(
            organization_slug=organization_slug,
            project_slug=project_slug)

        filename = os.path.join(
            filename,
            'information.json'
        )

        if relationship_layer_id:
            information['relationship_layer_id'] = relationship_layer_id

        if party_layer_id:
            information['party_layer_id'] = party_layer_id

        if vlayers:
            information['layers'] = []
            for layer in vlayers:
                layer_type = ''
                if layer.geometryType() == QGis.Point:
                    layer_type = 'Point'
                elif layer.geometryType() == QGis.Polygon:
                    layer_type = 'Polygon'
                elif layer.geometryType() == QGis.Line:
                    layer_type = 'Line'
                information['layers'].append(
                    {
                        'id': layer.id(),
                        'type': layer_type
                    }
                )

        file_ = open(filename, 'w')
        file_.write(json.dumps(information, sort_keys=True))
        file_.close()