Commit 14c9de8a authored by michelek's avatar michelek
Browse files

refactor to comply with new electron

parent 15a248a5
{
"folders": [
{
"path": "."
},
{
"path": "../entulib"
}
],
"settings": {}
}
\ No newline at end of file
......@@ -4,68 +4,67 @@ const util = require('util')
const { app, clipboard, BrowserWindow, ipcMain } = require('electron')
var windows = {}
var mainWindow
let mainWindow
var userUrl = 'https://entu.keeleressursid.ee/api2/user'
var authUrl = userUrl + '/auth'
const userUrl = 'https://entu.keeleressursid.ee/api2/user'
const authUrl = userUrl + '/auth'
const ISDEV = process.env.DEV ? true : false
ISDEV = process.env.DEV ? true : false
var pjsonPath = path.join(__dirname, '..', 'package.json')
var pjson = require(pjsonPath)
const pjsonPath = path.join(__dirname, '..', 'package.json')
let pjson = require(pjsonPath)
if (ISDEV) {
pjson.build++
fs.writeFileSync(pjsonPath, JSON.stringify(pjson, null, 2))
}
console.log('----==== ' + pjson.name + ' v.' + pjson.version + ' (build ' + (pjson.build) + ') ====----')
const appBuildNr = pjson.build
const appVersion = pjson.version
const appName = pjson.name
console.log('----==== ' + appName + ' v.' + appVersion + ' (build ' + (appBuildNr) + ') ====----')
const authWindowTitle = appName + ' v.' + appVersion + (appVersion.indexOf('-') > -1 ? appBuildNr : '') + ' | Logi sisse'
const appWebPreferences = {
partition: 'persist:panustaja (build ' + (pjson.build) + ')',
pageVisibility: true
partition: 'persist:panustaja (build ' + (appBuildNr) + ')',
pageVisibility: true,
worldSafeExecuteJavaScript: true
}
const rendererWebPreferences = {
partition: 'persist:panustaja (build ' + (pjson.build) + ')',
partition: 'persist:panustaja (build ' + (appBuildNr) + ')',
pageVisibility: true,
nodeIntegration: true,
enableRemoteModule: true
enableRemoteModule: true,
worldSafeExecuteJavaScript: true
}
app.on('ready', function() {
const authWin = new BrowserWindow({
width: 600,
height: 900,
width: 793, height: 490,
webPreferences: appWebPreferences
})
authWin.loadURL(authUrl, {userAgent: 'Chrome'})
var title = pjson.name + ' v.' + pjson.version + (pjson.version.indexOf('-') > -1 ? pjson.build : '') + ' | Logi sisse'
authWin.center()
authWin.setTitle(title)
authWin.setTitle(authWindowTitle)
authWin.webContents.on('did-get-response-details', function(e, s, newUrl) {
authWin.setTitle(title)
authWin.setTitle(authWindowTitle)
if (newUrl === userUrl || newUrl === userUrl + '#') {
authWin.hide()
}
})
authWin.webContents.on('did-finish-load', function() {
authWin.setTitle(title)
var newUrl = authWin.webContents.getURL()
authWin.setTitle(authWindowTitle)
const newUrl = authWin.webContents.getURL()
if (newUrl === userUrl || newUrl === userUrl + '#') {
clipboard.clear()
authWin.webContents.selectAll()
authWin.webContents.copy()
setTimeout(function () {
mainWindow = new BrowserWindow({ width: 900, height: 600, show: true, webPreferences: rendererWebPreferences })
mainWindow = new BrowserWindow({ width: 793, height: 490, show: true, webPreferences: rendererWebPreferences })
mainWindow.setTitle('Panustaja')
mainWindow.center()
var viewPath = path.join(app.getAppPath(), 'code', 'panuView.html')
const viewPath = path.join(app.getAppPath(), 'code', 'panuView.html')
mainWindow.webContents.loadURL('file://' + viewPath)
if (ISDEV) {
mainWindow.webContents.openDevTools(true)
......
......@@ -194,8 +194,8 @@ if (!data) {
clipboard.clear()
ipcRenderer.send('setUser', data)
}
if (op.get(data, 'result.user_id', false)) {
userData.userId = op.get(data, 'result.user_id')
if (op.get(data, 'result.id', false)) {
userData.userId = op.get(data, 'result.id')
userData.sessionKey = op.get(data, 'result.session_key')
userData.name = op.get(data, 'result.name')
document.getElementById('userName').innerHTML = userData.name
......
......@@ -5,6 +5,7 @@
<link rel="stylesheet" type="text/css" href="./style.css">
<link rel="icon" type="image/png" href="/images/murakas.ico" sizes="96x96">
<link rel="shortcut icon" href="/images/murakas.ico">
<meta http-equiv="Content-Security-Policy" content="script-src 'self';">
</head>
<body>
<div id="murakas">
......
var request = require('request')
var fs = require('fs')
var op = require('object-path')
var path = require('path')
var async = require('async')
const querystring = require('querystring')
const https = require('https')
const FormData = require('form-data')
const fs = require('fs')
const op = require('object-path')
const path = require('path')
const async = require('async')
const { shell } = require('electron').remote
// var remote = require('remote')
// var dialog = remote.require('dialog')
const b2s = require(path.join(__dirname, '..', 'code', 'bytesToSize.js'))
var b2s = require(path.join(__dirname, '..', 'code', 'bytesToSize.js'))
const resourceRootEid = 4387
const ENTUHOSTNAME = 'entu.keeleressursid.ee'
const ENTITYAPIPATHNAME = '/api2/entity'
const FILEAPIPATHNAME = '/api2/file'
var resourceRootEid = 4387
var uploadedResourcesProgress
var uploadedFilesProgress
ENTUAPI = 'https://entu.keeleressursid.ee/api2'
ENTUAPIENTITY = 'https://entu.keeleressursid.ee/api2/entity'
ENTUAPIFILE = 'https://entu.keeleressursid.ee/api2/file'
var rendererInterval
var fileUploadTasks = []
......@@ -33,121 +31,128 @@ function renderProgress() {
}
function addEntuFile(eid, filePath, callback) {
function addEntuFile(eid, filePath, resource, callback) {
// console.log('U: Uploading file ' + filePath + ' at resource ' + eid)
var options = {
url: ENTUAPIFILE,
headers: {
'X-Auth-UserId': userData.userId,
'X-Auth-Token': userData.sessionKey,
'User-Agent': UPLOADERVERSION
}
const headers = {
'X-Auth-UserId': userData.userId,
'X-Auth-Token': userData.sessionKey,
'User-Agent': UPLOADERVERSION,
'X-FILENAME': path.basename(filePath),
'X-ENTITY': eid,
'X-PROPERTY': 'resource-file'
}
// var req = request.post(options, function (err, resp, body) {
var req = request.post(options, function (err) {
// console.log(err, resp, JSON.parse(body))
if (err) {
callback(err)
// } else if (resp.status.statusCode !== 200) { callback(body) }
} else {
// console.log('URL: ' + body)
callback()
}
const readStream = fs.createReadStream(filePath)
readStream.on('data', function(chunk) {
uploadedFilesProgress += chunk.length
})
readStream.on('end', function () {
// console.log('finished stream', req)
req.end()
})
var form = req.form()
var readStream = fs.createReadStream(filePath)
form.append('file', readStream)
const form = new FormData()
form.append('entity', eid)
form.append('property', 'resource-file')
form.append('filename', path.basename(filePath))
readStream.on('data', function(chunk) {
uploadedFilesProgress += chunk.length
// console.log('Uploaded: ' + uploadedFilesProgress + '(+' + chunk.length + ')')
})
}
function addEntuProperties(eid, data, callback) {
request.put({
url: preparedUrl,
headers: headers,
body: qb,
strictSSL: true,
json: true,
timeout: 60000
}, function(error, response, body) {
if(error) return callback(error)
if(response.statusCode !== 201 || !body.result) return callback(new Error(op.get(body, 'error', body)))
callback(null, op.get(body, 'result.properties.' + property + '.0', null))
form.append('file', readStream)
// console.log('form with entity', eid, form)
let options = {
hostname: ENTUHOSTNAME,
path: FILEAPIPATHNAME,
method: 'POST',
headers: headers
}
const req = https.request(options, response => {
// console.log('Status', response.statusCode)
// if (response.statusCode !== 201) {
// return callback(new Error(op.get(postData, 'error', postData)))
// }
let body = ''
response.setEncoding('utf8')
response.on('data', (chunk) => { body = body + chunk })
response.on('end', () => {
body = JSON.parse(body)
// console.log('Response body', body)
})
callback()
})
req.on('error', (e) => { return callback(e) })
var urlData = Object.keys(data).map(function (ix) {return ix + '=' + data[ix]}).join('&')
// console.log(urlData)
var xhr = new window.XMLHttpRequest()
xhr.open('PUT', ENTUAPIENTITY + '-' + eid + '?' + urlData, true)
xhr.setRequestHeader('X-Auth-UserId', userData.userId)
xhr.setRequestHeader('X-Auth-Token', userData.sessionKey)
xhr.onload = function () {
// var response = JSON.parse(this.responseText)
// console.log(JSON.stringify({sent:data, got:response}, null, 4))
callback()
}
xhr.onerror = function(err) {
callback('ERROR: ' + err)
}
xhr.send(data)
form.pipe(req)
postData = querystring.stringify({'entity': eid})
req.write(postData)
// req.end()
}
function createEntuResource(parentEid, resource, callback) {
// console.log('create under EID:', parentEid)
// console.log('resource::', op.get(resource))
var body = {
let postData = {
'definition': 'resource',
'resource-name': path.basename(op.get(resource, ['name'], 'nameless resource')),
'resource-uploader-version': UPLOADERVERSION
}
if (op.get(resource, ['mime-encode'], false)) {
op.set(body, ['resource-mime-encode'], op.get(resource, ['mime-encode']))
op.set(postData, ['resource-mime-encode'], op.get(resource, ['mime-encode']))
}
if (op.get(resource, ['size'], false)) {
op.set(body, ['resource-size'], op.get(resource, ['size']))
op.set(postData, ['resource-size'], op.get(resource, ['size']))
}
postData = querystring.stringify(postData)
var preparedUrl = ENTUAPIENTITY + '-' + parentEid
var headers = {'X-Auth-UserId': userData.userId, 'X-Auth-Token': userData.sessionKey}
// console.log('Try to execute URL ' + preparedUrl, userData, body)
request.post({
url: preparedUrl,
headers: headers,
body: body,
strictSSL: true,
json: true,
timeout: 60000
}, function(error, response, body) {
// console.log('result', body)
if(error) return callback(error)
if(response.statusCode !== 201) return callback(new Error(op.get(body, 'error', body)))
var newEid = body.result.id
uploadedResourcesProgress++
op.get(resource, ['files'], []).forEach(function(filePath) {
fileUploadTasks.push(function uploadFile(callback) {
document.getElementById('status').innerHTML = newEid + ' : ' + filePath
// console.log('F: Uploading file ' + filePath + ' at resource ' + newEid)
addEntuFile(newEid, filePath, function fileAddedCB() {
callback()
const headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': postData.length,
'X-Auth-UserId': userData.userId,
'X-Auth-Token': userData.sessionKey
}
const options = {
hostname: ENTUHOSTNAME,
path: ENTITYAPIPATHNAME + '-' + parentEid,
method: 'POST',
headers: headers
}
// console.log('Request with options ', options)
const req = https.request(options, (res) => {
// console.log('RES:', res)
// console.log('HEADERS:' ${JSON.stringify(res.headers)}`)
if (res.statusCode !== 201) {
return callback(new Error(op.get(postData, 'error', postData)))
}
let body = ''
res.setEncoding('utf8')
res.on('data', (chunk) => { body = body + chunk })
res.on('end', () => {
body = JSON.parse(body)
// console.log('Response body', body)
var newEid = body.result.id
uploadedResourcesProgress++
op.get(resource, ['files'], []).forEach(function(filePath) {
fileUploadTasks.push(function uploadFile(callback) {
document.getElementById('status').innerHTML = newEid + ' : ' + filePath
// console.log('F: Uploading file ' + filePath + ' at resource ' + newEid)
addEntuFile(newEid, filePath, resource, function fileAddedCB() {
callback()
})
})
// console.log('F: Queued file ' + filePath + ' for upload at resource ' + newEid)
})
// console.log('F: Queued file ' + filePath + ' for upload at resource ' + newEid)
callback(null, newEid)
})
callback(null, newEid)
})
req.on('error', (e) => { return callback(e) })
req.write(postData)
req.end()
}
function recurseResources(parentEid, resource, resourcesCreatedCB) {
......@@ -181,13 +186,16 @@ function upload() {
function runRecurseResources(callback) {
recurseResources(resourceRootEid, resource, function resourcesCreated(err, newEid) {
if (err) { return callback(err) }
// console.log('resources created; eid', newEid)
callback(null, newEid)
})
},
function runFileUploadTasks(newEid, callback) {
async.parallelLimit(fileUploadTasks, 3, function filesUploaded() { callback(null, newEid) })
// console.log('runFileUploadTasks; eid', newEid)
async.parallelLimit(fileUploadTasks, 1, function filesUploaded() { callback(null, newEid) })
},
function updateUI(newEid, callback) {
// console.log('set form state uploaded; eid', newEid)
setFormState('uploaded')
document.getElementById('resourceEntuLink').setAttribute('href', 'https://entu.keeleressursid.ee/entity/resource/' + newEid)
document.getElementById('resourceEntuLink').innerHTML = 'https://entu.keeleressursid.ee/entity/resource/' + newEid
......@@ -205,5 +213,4 @@ function upload() {
}
module.exports.upload = upload
......@@ -714,12 +714,12 @@
"integrity": "sha1-+8cfDEGt6zf5bFd60e1C2P2sypE="
},
"form-data": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz",
"integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==",
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-3.0.0.tgz",
"integrity": "sha512-CKMFDglpbMi6PyN+brwB9Q/GOw0eAnsrEZDgcsH5Krhz5Od/haKHAX0NmQfha2zPPz0JpWzA7GJHGSnvCRLWsg==",
"requires": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.6",
"combined-stream": "^1.0.8",
"mime-types": "^2.1.12"
}
},
......@@ -1461,6 +1461,18 @@
"tough-cookie": "~2.5.0",
"tunnel-agent": "^0.6.0",
"uuid": "^3.3.2"
},
"dependencies": {
"form-data": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz",
"integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==",
"requires": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.6",
"mime-types": "^2.1.12"
}
}
}
},
"resolve": {
......
......@@ -17,6 +17,7 @@
},
"dependencies": {
"async": "^1.5.0",
"form-data": "^3.0.0",
"mime": "^1.3.4",
"object-path": "^0.9.2",
"request": "^2.65.0"
......@@ -25,4 +26,4 @@
"electron": "^10.1.1",
"electron-packager": "^15.1.0"
}
}
\ No newline at end of file
}
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment