Skip to content

Commit

Permalink
- Change privacy for maps, (public checkbox).
Browse files Browse the repository at this point in the history
- Change some texts.
  • Loading branch information
elesdoar committed Sep 2, 2015
1 parent 2998433 commit bb2cbda
Show file tree
Hide file tree
Showing 13 changed files with 397 additions and 307 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
<a name="0.2.2"></a>
### 0.2.2 (2015-09-02)

#### Enhancements

* Change privacy for maps (public checkbox).
* Change some texts.

<a name="0.2.1"></a>
### 0.2.1 (2015-08-19)

Expand Down
13 changes: 13 additions & 0 deletions cartodb/cartodbapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ def __init__(self, cartodbUser, apiKey, multiuser=False, hostname='cartodb.com')
self.cartodbUser = cartodbUser
self.hostname = hostname
self.apiUrl = "https://{}.{}/api/v1/".format(cartodbUser, hostname)
self.returnDict = True

self.manager = QNetworkAccessManager()
self.manager.finished.connect(self.returnFetchContent)
Expand Down Expand Up @@ -180,6 +181,18 @@ def createVizFromTable(self, table, name, description='', returnDict=True):
reply.finished.connect(loop.exit)
loop.exec_()

def updateViz(self, viz, returnDict=True):
self.returnDict = returnDict
url = QUrl(self.apiUrl + "viz/{}?api_key={}".format(viz['id'], self.apiKey))
request = self._getRequest(url)

reply = self.manager.put(request, json.dumps(viz))
loop = QEventLoop()
reply.downloadProgress.connect(self.progressCB)
reply.error.connect(self._error)
reply.finished.connect(loop.exit)
loop.exec_()

def addLayerToMap(self, mapId, layer, returnDict=True):
self.returnDict = returnDict
url = QUrl(self.apiUrl + "maps/{}/layers?api_key={}".format(mapId, self.apiKey))
Expand Down
293 changes: 141 additions & 152 deletions dialogs/CreateViz.py

Large diffs are not rendered by default.

183 changes: 52 additions & 131 deletions dialogs/Upload.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
"""
/***************************************************************************
CartoDB Plugin
A QGIS plugin
----------------------------------------------------------------------------
begin : 2014-09-08
Expand All @@ -18,25 +17,26 @@
* *
***************************************************************************/
"""
from PyQt4.QtCore import Qt, QSettings, QFile, QFileInfo, QTimer, QVariant, pyqtSignal, pyqtSlot, qDebug
from PyQt4.QtGui import QApplication, QDialog, QPixmap, QListWidgetItem, QLabel, QSizePolicy
from PyQt4.QtCore import QTimer, pyqtSignal, qDebug
from PyQt4.QtGui import QApplication, QDialog, QListWidgetItem, QSizePolicy

from qgis.core import QgsMapLayerRegistry, QgsMapLayer, QgsVectorFileWriter, QgsField, QgsVectorLayer
from qgis.core import QgsMapLayerRegistry, QgsMapLayer, QgsVectorFileWriter
from qgis.gui import QgsMessageBar

# pylint: disable-msg=F0401
from QgisCartoDB.cartodb import CartoDBApi
from QgisCartoDB.layers import CartoDBLayer
from QgisCartoDB.dialogs.Basic import CartoDBPluginUserDialog
from QgisCartoDB.ui.Upload import Ui_Upload
from QgisCartoDB.utils import getSize, checkTempDir, zipLayer, checkCartoDBId
from QgisCartoDB.widgets import CartoDBLayerListItem

import math
import os
import tempfile
import zipfile


class CartoDBPluginUpload(CartoDBPluginUserDialog):
"""Dialog for Upload data to CartoDB"""
addedLayer = pyqtSignal(str, str)

def __init__(self, iface, toolbar, parent=None):
Expand All @@ -53,6 +53,7 @@ def __init__(self, iface, toolbar, parent=None):

self.ui.uploadBT.clicked.connect(self.upload)
self.ui.cancelBT.clicked.connect(self.reject)
self.ui.layersList.itemSelectionChanged.connect(self.validateButtons)

layers = QgsMapLayerRegistry.instance().mapLayers()

Expand All @@ -64,24 +65,27 @@ def __init__(self, iface, toolbar, parent=None):
self.ui.uploadBar.setValue(0)
self.ui.uploadBar.hide()
self.ui.uploadingLB.hide()
for id, ly in layers.iteritems():
for id_ly, ly in layers.iteritems():
qDebug('Layer id {}'.format(id_ly))
if ly.type() == QgsMapLayer.VectorLayer and not isinstance(ly, CartoDBLayer):
item = QListWidgetItem(self.ui.layersList)
widget = CartoDBLayerListItem(ly.name(), ly, self.getSize(ly), ly.dataProvider().featureCount())
widget = CartoDBLayerListItem(ly.name(), ly, getSize(ly), ly.dataProvider().featureCount())
item.setSizeHint(widget.sizeHint())
self.ui.layersList.setItemWidget(item, widget)

def upload(self):
registry = QgsMapLayerRegistry.instance()
for layerItem in self.ui.layersList.selectedItems():
widget = self.ui.layersList.itemWidget(layerItem)
"""Init upload proccess"""
for layer_item in self.ui.layersList.selectedItems():
widget = self.ui.layersList.itemWidget(layer_item)
qDebug('Layer: ' + str(widget.layer.storageType()))
layer = self.checkCartoDBId(widget.layer, self.ui.convertCH.isChecked())
zipPath = self.zipLayer(layer)
self.uploadZip(zipPath, widget, layer, self.ui.convertCH.isChecked())
layer = checkCartoDBId(widget.layer, self.ui.convertCH.isChecked())
zip_path = zipLayer(layer)
self.uploadZip(zip_path, widget, layer, self.ui.convertCH.isChecked())

def uploadZip(self, zipPath, widget, convertLayer=None, convert=False):
def uploadZip(self, zip_path, widget, convertLayer=None, convert=False):
"""Upload Zipfile"""
def completeUpload(data):
"""On complete upload"""
timer = QTimer(self)

self.ui.uploadBar.hide()
Expand All @@ -91,155 +95,72 @@ def completeUpload(data):
self.ui.bar.pushMessage(QApplication.translate('CartoDBPlugin', 'Upload Complete'),
level=QgsMessageBar.INFO, duration=5)

def statusComplete(d):
if d['state'] == 'complete':
def statusComplete(res):
"""On CartoDB import proccess complete o fail"""
if res['state'] == 'complete':
timer.stop()
self.ui.statusLB.setText(QApplication.translate('CartoDBPlugin', 'Ready'))
widget.setStatus(d['state'], 100)
widget.setStatus(res['state'], 100)
self.ui.bar.clearWidgets()
self.ui.bar.pushMessage(QApplication.translate('CartoDBPlugin', 'Table {} created').format(d['table_name']),
self.ui.bar.pushMessage(QApplication.translate('CartoDBPlugin', 'Table {} created').format(res['table_name']),
level=QgsMessageBar.INFO, duration=5)

if convert:
self.convert2CartoDB(convertLayer if convertLayer is not None else widget.layer, d['table_name'])
elif d['state'] == 'failure':
self.convert2CartoDB(convertLayer if convertLayer is not None else widget.layer, res['table_name'])
elif res['state'] == 'failure':
timer.stop()
self.ui.statusLB.setText(QApplication.translate('CartoDBPlugin', '{} failed, {}').format(
widget.layer.name(), d['get_error_text']['title']))
widget.setStatus(d['state'])
widget.layer.name(), res['get_error_text']['title']))
widget.setStatus(res['state'])
self.ui.bar.clearWidgets()
self.ui.bar.pushMessage(QApplication.translate('CartoDBPlugin', 'Error uploading {}').format(widget.layer.name()),
level=QgsMessageBar.WARNING, duration=5)
else:
widget.setStatus(d['state'])
widget.setStatus(res['state'])

def timerComplete():
cartodbApi = CartoDBApi(self.currentUser, self.currentApiKey, self.currentMultiuser)
cartodbApi.fetchContent.connect(statusComplete)
cartodbApi.checkUploadStatus(data['item_queue_id'])
"""On timer complete, check import process in CartoDB Servers"""
# pylint: disable-msg=E1101
cartodb_api = CartoDBApi(self.currentUser, self.currentApiKey, self.currentMultiuser)
cartodb_api.fetchContent.connect(statusComplete)
cartodb_api.checkUploadStatus(data['item_queue_id'])

timer.timeout.connect(timerComplete)
timer.start(500)

cartodbApi = CartoDBApi(self.currentUser, self.currentApiKey, self.currentMultiuser)
cartodbApi.fetchContent.connect(completeUpload)
cartodbApi.progress.connect(self.progressUpload)

# pylint: disable-msg=E1101
cartodb_api = CartoDBApi(self.currentUser, self.currentApiKey, self.currentMultiuser)
cartodb_api.fetchContent.connect(completeUpload)
cartodb_api.progress.connect(self.progressUpload)
self.ui.uploadBar.show()
self.ui.uploadBT.setEnabled(False)
self.ui.uploadingLB.setText(QApplication.translate('CartoDBPlugin', 'Uploading {}').format(widget.layer.name()))
self.ui.uploadingLB.show()
self.ui.bar.clearWidgets()
cartodbApi.upload(zipPath)
cartodb_api.upload(zip_path)

def convert2CartoDB(self, layer, tableName):
self.checkTempDir()
tf = tempfile.NamedTemporaryFile()
qDebug('New file {}'.format(tf.name))
error = QgsVectorFileWriter.writeAsVectorFormat(layer, tf.name, "utf-8", None, "SQLite")
"""Convert QGIS styles to CartoCSS"""
checkTempDir()
temp = tempfile.NamedTemporaryFile()
qDebug('New file {}'.format(temp.name))
error = QgsVectorFileWriter.writeAsVectorFormat(layer, temp.name, "utf-8", None, "SQLite")
if error == QgsVectorFileWriter.NoError:
self.addedLayer.emit(tf.name + '.sqlite', tableName)
self.addedLayer.emit(temp.name + '.sqlite', tableName)
else:
self.ui.bar.pushMessage(QApplication.translate('CartoDBPlugin', 'Error loading CartoDB layer {}').format(tableName),
level=QgsMessageBar.WARNING, duration=5)

def progressUpload(self, current, total):
"""Check upload proccess"""
self.ui.uploadBar.setValue(math.ceil(float(current)/float(total)*100))

def getSize(self, layer):
isZipFile = False
filePath = layer.dataProvider().dataSourceUri()
if filePath.find('|') != -1:
filePath = filePath[0:filePath.find('|')]

if filePath.startswith('/vsizip/'):
filePath = filePath.replace('/vsizip/', '')
isZipFile = True

file = QFile(filePath)
fileInfo = QFileInfo(file)

dirName = fileInfo.dir().absolutePath()
fileName = fileInfo.completeBaseName()

size = 0
if layer.storageType() == 'ESRI Shapefile' and not isZipFile:
for suffix in ['.shp', '.dbf', '.prj', '.shx']:
file = QFile(os.path.join(dirName, fileName + suffix))
fileInfo = QFileInfo(file)
size = size + fileInfo.size()
elif layer.storageType() in ['GPX', 'GeoJSON', 'LIBKML'] or isZipFile:
size = size + fileInfo.size()

return size

def checkCartoDBId(self, layer, convert = False):
ly = layer

if convert and layer.fieldNameIndex('cartodb_id') == -1:
self.checkTempDir()
tf = tempfile.NamedTemporaryFile()
error = QgsVectorFileWriter.writeAsVectorFormat(layer, tf.name, 'utf-8', None, 'ESRI Shapefile')
if error == QgsVectorFileWriter.NoError:
ly = QgsVectorLayer(tf.name + '.shp', layer.name(), 'ogr')
res = ly.dataProvider().addAttributes([QgsField('cartodb_id', QVariant.Int)])
ly.updateFields()
features = ly.getFeatures()
i = 1
for f in features:
fid = f.id()
aid = ly.fieldNameIndex('cartodb_id')
attrs = { aid: i }
ly.dataProvider().changeAttributeValues({ fid : attrs })
i = i + 1
ly.updateFeature(f)
return ly

def zipLayer(self, layer):
filePath = layer.dataProvider().dataSourceUri()
if filePath.find('|') != -1:
filePath = filePath[0:filePath.find('|')]

if filePath.startswith('/vsizip/'):
filePath = filePath.replace('/vsizip/', '')
if layer.storageType() in ['ESRI Shapefile', 'GPX', 'GeoJSON', 'LIBKML']:
return filePath

file = QFile(filePath)
fileInfo = QFileInfo(file)

dirName = fileInfo.dir().absolutePath()
fileName = fileInfo.completeBaseName()

tempdir = self.checkTempDir()

zipPath = os.path.join(tempdir, layer.name() + '.zip')
zipFile = zipfile.ZipFile(zipPath, 'w')


if layer.storageType() == 'ESRI Shapefile':
for suffix in ['.shp', '.dbf', '.prj', '.shx']:
if os.path.exists(os.path.join(dirName, fileName + suffix)):
zipFile.write(os.path.join(dirName, fileName + suffix), layer.name() + suffix, zipfile.ZIP_DEFLATED)
elif layer.storageType() == 'GeoJSON':
zipFile.write(filePath, layer.name() + '.geojson', zipfile.ZIP_DEFLATED)
elif layer.storageType() == 'GPX':
zipFile.write(filePath, layer.name() + '.gpx', zipfile.ZIP_DEFLATED)
elif layer.storageType() == 'LIBKML':
zipFile.write(filePath, layer.name() + '.kml', zipfile.ZIP_DEFLATED)
else:
geoJsonName = os.path.join(tempfile.tempdir, layer.name())
error = QgsVectorFileWriter.writeAsVectorFormat(layer, geoJsonName, "utf-8", None, "GeoJSON")
if error == QgsVectorFileWriter.NoError:
zipFile.write(geoJsonName + '.geojson', layer.name() + '.geojson', zipfile.ZIP_DEFLATED)
zipFile.close()
return zipPath

def reject(self):
# Back out of dialogue
"""Back out of dialogue"""
QDialog.reject(self)

def checkTempDir(self):
tempdir = tempfile.tempdir
if tempdir is None:
tempdir = tempfile.mkdtemp()
return tempdir
def validateButtons(self):
"""Validate upload button"""
enabled = self.ui.layersList.count() > 0
self.ui.uploadBT.setEnabled(enabled)
14 changes: 7 additions & 7 deletions i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@
<translation>Filter Tables</translation>
</message>
<message>
<source>Import data by current extent</source>
<translation>Import data by current extent</translation>
<source>Download data only within the current view</source>
<translation>Download data only within the current view</translation>
</message>
<message>
<source>Name</source>
Expand Down Expand Up @@ -214,8 +214,8 @@
<translation>Replace if exists</translation>
</message>
<message>
<source>Add CartoDB layer to project (this could truncate the column's names)</source>
<translation>Add CartoDB layer to project (this could truncate the column's names)</translation>
<source>Add CartoDB layer to project</source>
<translation>Add CartoDB layer to project</translation>
</message>
<message>
<source>Cancel</source>
Expand All @@ -227,7 +227,7 @@
</message>
<message>
<source>Ready</source>
<translation>Listo</translation>
<translation>Ready</translation>
</message>
</context>
<context>
Expand Down Expand Up @@ -277,8 +277,8 @@
<translation>Create</translation>
</message>
<message>
<source>Make Public</source>
<translation>Make Public</translation>
<source>Public</source>
<translation>Public</translation>
</message>
</context>
<context>
Expand Down
12 changes: 6 additions & 6 deletions i18n/es.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@
<translation>Filtrar Tablas</translation>
</message>
<message>
<source>Import data by current extent</source>
<translation>Importar datos por la extensión actual</translation>
<source>Download data only within the current view</source>
<translation>Descargar datos únicamente dentro de la vista actual</translation>
</message>
<message>
<source>Name</source>
Expand Down Expand Up @@ -214,8 +214,8 @@
<translation>Reemplazar si existe en CartoDB</translation>
</message>
<message>
<source>Add CartoDB layer to project (this could truncate the column's names)</source>
<translation>Agregar capa CartoDB al proyecto (esto podría truncar los nombres de las columnas)</translation>
<source>Add CartoDB layer to project</source>
<translation>Agregar capa CartoDB al proyecto</translation>
</message>
<message>
<source>Cancel</source>
Expand Down Expand Up @@ -277,8 +277,8 @@
<translation>Crear</translation>
</message>
<message>
<source>Make Public</source>
<translation>Hacer público</translation>
<source>Public</source>
<translation>Público</translation>
</message>
</context>
<context>
Expand Down
Loading

0 comments on commit bb2cbda

Please sign in to comment.