Skip to content

Commit

Permalink
add working photos support
Browse files Browse the repository at this point in the history
  • Loading branch information
YasiOnFire committed Mar 13, 2021
1 parent c755ad1 commit 377ddbc
Show file tree
Hide file tree
Showing 3 changed files with 151 additions and 10 deletions.
2 changes: 1 addition & 1 deletion package.json
@@ -1,6 +1,6 @@
{
"name": "eb2st",
"version": "0.0.1",
"version": "0.0.2",
"description": "Convert endomondo backup to gpx and automagicaly import to SportsTracker",
"productName": "EndomondoBackup2SportsTracker",
"author": "Yasio <baszczok@yasio.pl>",
Expand Down
105 changes: 102 additions & 3 deletions src-electron/main-process/electron-main.js
Expand Up @@ -205,6 +205,7 @@ ipcMain.on('convert-all-workouts', async (event, args) => {
await waitFor(2);
await wait('.select-activity');
const woKeys = [];
[...document.querySelectorAll('[selected-date]')].forEach(el => {
const parent = el.closest('ul');
console.log('parent: ', parent);
Expand All @@ -215,6 +216,10 @@ ipcMain.on('convert-all-workouts', async (event, args) => {
console.log('newVal: ', newVal);
parent.querySelector('.select-activity option[selected]').remove();
parent.querySelector('.select-activity option[label="'+newVal+'"]')?.setAttribute('selected', 'selected');
woKeys.push({
timestamp: el.attributes['selected-date'].value,
key: el.attributes['workout-key'].value
})
}
}
})
Expand All @@ -225,10 +230,11 @@ ipcMain.on('convert-all-workouts', async (event, args) => {
document.querySelector('.save-button').dispatchEvent(new Event('click'));
//await waitFor(2);
console.log('done');
return woKeys;
}
init();
`).then(() => {
event.reply('asynchronous-reply', { part: true, action: 'convert-all-workouts', payload: 'success' })
init().then(r => r);
`).then((result) => {
event.reply('asynchronous-reply', { part: true, action: 'convert-all-workouts', payload: result })
setTimeout(() => {
win.destroy()
}, 2000)
Expand All @@ -243,3 +249,96 @@ ipcMain.on('convert-all-workouts', async (event, args) => {
console.error(error)
}
})

ipcMain.on('upload-photos', async (event, args) => {
try {
const { dir, workout, login, passwd } = JSON.parse(args)

const fileBuffers = []
for await (const photos of workout.pictures) {
const f = await fs.readFileSync(`${dir}\\${photos}`, null)
fileBuffers.push(f.toString('base64'))
}

const win = new BrowserWindow({
show: false,
webPreferences: {
nodeIntegration: false,
devTools: true
}
})

win.loadURL('https://www.sports-tracker.com/login')
event.reply('asynchronous-reply', { update: 'Start photo upload', action: 'upload-photos', payload: 'success' })

await win.webContents.on('did-finish-load', async (evt, result) => {
await win.webContents.on('did-navigate', async (evt, url) => {
if (url.indexOf('workout') > -1) {
console.log('url: ', url);
win.webContents.executeJavaScript(`
const init2 = async () => {
const wait = async (selector) => {
while(!document.querySelector(selector)) {
await new Promise(r => setTimeout(r, 1500));
}
}
const waitFor = async (seconds) => {
await new Promise(r => setTimeout(r, seconds * 1000));
}
const dt = new DataTransfer();
const x = [${fileBuffers.map(d => `'${d}'`)}];
await wait('#workout-image-add-input');
for (const item of x) {
const response = await fetch('data:image/jpeg;base64,' + item);
const file = new File([await response.blob()], 'yasio.jpg', {type: 'image/jpeg'});
dt.items.add(file);
}
document.querySelector('#workout-image-add-input').files = dt.files;
await waitFor(2);
document.querySelector('#workout-image-add-input').dispatchEvent(new Event('change', { bubbles: true }));
await wait('.workout-image-link')
}
init2()
`).then(() => {
event.reply('asynchronous-reply', { part: true, action: 'upload-photos', payload: 'true' })
setTimeout(() => {
win.destroy()
}, 1000)
})

}
})
win.webContents.executeJavaScript(`
const init = async () => {
const wait = async (selector) => {
while(!document.querySelector(selector)) {
await new Promise(r => setTimeout(r, 1500));
}
}
const waitFor = async (seconds) => {
await new Promise(r => setTimeout(r, seconds * 1000));
}
const payload = JSON.parse('${JSON.stringify(workout)}');
if (document.querySelector('.username') && document.querySelector('.password')) {
document.querySelector('.username').value = '${login}';
document.querySelector('.password').value = '${passwd}';
document.querySelector('.submit').dispatchEvent(new Event('click'));
}
await wait('.add-workout');
// tutaj te fecze w pętli
const user = document.querySelector('a[href^="/view_profile"]').href.substr(document.querySelector('a[href^="/view_profile"]').href.lastIndexOf('/') + 1);
window.location.href = 'https://www.sports-tracker.com/workout/' + user + '/' + payload.key;
};
init();
`)
});

} catch (error) {
event.reply('asynchronous-reply', { error: true, errorMessage: JSON.stringify(error), action: 'upload-photos' })
console.error(error)
}
})
54 changes: 48 additions & 6 deletions src/pages/Index.vue
Expand Up @@ -58,7 +58,7 @@
:pagination="{
rowsPerPage: 100
}"
:data="data"
:data="edata"
row-key="file"
:columns="[
{
Expand Down Expand Up @@ -176,7 +176,7 @@
<q-stepper-navigation>
<q-btn size="lg" v-if="step > 1 && step < 4" flat color="deep-orange" @click="step--" label="Back" class="q-mr-md" />
<q-btn size="lg" v-if="step === 4" flat color="deep-orange" @click="step = 1" :disabled="loaders.button" label="Start Over" class="q-mr-md" />
<q-btn size="lg" :disabled="invalidStep || loaders.button" :loading="loaders.button" @click="nextStep" color="primary" :label="step === 4 ? 'Restart' : 'Continue'" />
<q-btn size="lg" :disabled="invalidStep || loaders.button" :loading="loaders.button" @click="nextStep" color="primary" :label="step === 4 ? 'Restart process' : 'Continue'" />
</q-stepper-navigation>
</template>
</q-stepper>
Expand All @@ -192,14 +192,14 @@ export default {
name: 'PageIndex',
data () {
return {
data: [],
edata: [],
typeMap,
selectedWorkouts: [],
step: 1,
endoFolder: null,
login: process.env.VUE_DEFAULT_LOGIN || '',
passwd: process.env.VUE_DEFAULT_PASSWD || '',
code: 'Process started...\nThis might take a few minutes, the window may appear as frozen but unitl the loader is spinning the process is working.\nAs sports-tracker allows only 10 imports at once, this will import the workouts in batches of 10.\n\n',
code: 'Process started...\nThis might take a few minutes, the window may appear as frozen but unitl the loader is spinning the process is working.\nAs sports-tracker allows only 10 imports at once, this will import the workouts in batches of 10.\nAfter workout import, photo upload will begin.\n\n',
errors: {
file: false
},
Expand Down Expand Up @@ -288,6 +288,28 @@ export default {
passwd: this.passwd,
workoutList: this.toProcess[this.currIndex]
}))
} else {
setTimeout(() => {
this.currIndex = 0
this.toProcess = this.selectedWorkouts.filter(w => w.pictures && w.key).map(el => {
const pictures = el.pictures.flat()
return {
...el,
pictures: pictures.filter(p => p.picture).map(k => k.picture.flat()).flat().map(l => l.url)
}
})
this.uploadPhotos()
}, 2000)
}
},
uploadPhotos() {
if (this.currIndex < this.toProcess.length) {
this.ipcRenderer.send('upload-photos', JSON.stringify({
dir: this.endoDir,
login: this.login,
passwd: this.passwd,
workout: this.toProcess[this.currIndex]
}))
} else {
this.setLoading(false)
this.code += `\nProcess finished. Check your sports-tracker profile.`
Expand All @@ -312,14 +334,14 @@ export default {
if (arg.action && arg.action === 'read-all-workouts') {
if (arg.success) {
this.setLoading(false)
this.data = arg.payload.map((el, idx) => {
this.edata = arg.payload.map((el, idx) => {
return {
...el,
idx: idx + 1,
sporttracker: typeMap.find(t => t.label.toLowerCase() === el.sport.replace('_', ' ').toLowerCase()) ? typeMap.find(t => t.label.toLowerCase() === el.sport.replace('_', ' ').toLowerCase()).value : 'Running'
}
})
this.setEndoData(this.data)
this.setEndoData(this.edata)
}
}
if (arg.action && arg.action === 'validate-endo-dir') {
Expand All @@ -343,8 +365,28 @@ export default {
if (arg.part) {
this.code += `\nPart: ${this.currIndex + 1} finished importing`
this.currIndex++
console.log('arg.payload: ', arg.payload);
arg.payload.forEach(el => {
if (this.edata.find(d => d.timestamp == el.timestamp)) {
this.edata.find(d => d.timestamp == el.timestamp).key = el.key
}
if (this.selectedWorkouts.find(d => d.timestamp == el.timestamp)) {
this.selectedWorkouts.find(d => d.timestamp == el.timestamp).key = el.key
}
})
this.setEndoData(this.edata)
this.generate()
}
}
if (arg.action && arg.action === 'upload-photos') {
if (arg.update) {
this.code += `\n${arg.update} - ${JSON.stringify(arg.payload)}`
}
if (arg.part) {
this.code += `\nPart: ${this.currIndex + 1} uploaded`
this.currIndex++
this.uploadPhotos()
}
if (arg.success) {
this.setLoading(false)
this.loaders.button = false
Expand Down

0 comments on commit 377ddbc

Please sign in to comment.