Skip to content

Commit

Permalink
v0.5.5 pre-release 1
Browse files Browse the repository at this point in the history
  • Loading branch information
ItsRiprod committed Jul 18, 2024
1 parent ea88fe6 commit c1d1be2
Show file tree
Hide file tree
Showing 18 changed files with 569 additions and 48 deletions.
13 changes: 10 additions & 3 deletions AppExamples/spotify/builds/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13865,6 +13865,15 @@ var require_spotify = __commonJS({
const url = `${this.BASE_URL}/shuffle?state=${state}`;
return this.makeRequest("put", url);
}
async transfer() {
try {
if (this.settings.output_device.value !== "default" && this.settings.output_device.value) {
this.transferPlayback(this.settings.output_device.value);
}
} catch (error) {
this.sendError("Error changing playback!" + error);
}
}
async transferPlayback(deviceId) {
this.sendLog(`Transferring playback to ${deviceId}`);
const url = `${this.BASE_URL}`;
Expand Down Expand Up @@ -13895,9 +13904,6 @@ var require_spotify = __commonJS({
if (new_id === id) {
throw new Error("Timeout Reached!");
}
if (currentPlayback?.device.id !== null && this.settings.output_device.value !== "default" && this.settings.output_device.value !== currentPlayback?.device.id) {
this.transferPlayback(this.settings.output_device.value);
}
let songData;
if (currentPlayback.currently_playing_type === "track") {
songData = {
Expand Down Expand Up @@ -14090,6 +14096,7 @@ var handleGet = async (...args) => {
switch (args[0].toString()) {
case "song":
response = await spotify.returnSongData();
spotify.transfer();
break;
case "manifest":
response = spotify.manifest;
Expand Down
1 change: 1 addition & 0 deletions AppExamples/spotify/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ const handleGet = async (...args) => {
switch (args[0].toString()) {
case 'song':
response = await spotify.returnSongData()
spotify.transfer()
break
case 'manifest':
response = spotify.manifest
Expand Down
15 changes: 11 additions & 4 deletions AppExamples/spotify/spotify.js
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,17 @@ class SpotifyHandler {
const url = `${this.BASE_URL}/shuffle?state=${state}`
return this.makeRequest('put', url)
}

async transfer() {
try {
if (this.settings.output_device.value !== 'default' && this.settings.output_device.value) {
this.transferPlayback(this.settings.output_device.value);
this.sendLog('Transferred successfully')
}
} catch (error) {
this.sendError('Error changing playback!' + error)
}
}

async transferPlayback(deviceId) {
this.sendLog(`Transferring playback to ${deviceId}`)
Expand Down Expand Up @@ -381,10 +392,6 @@ class SpotifyHandler {
throw new Error('Timeout Reached!')
}

if (currentPlayback?.device.id !== null && this.settings.output_device.value !== 'default' && this.settings.output_device.value !== currentPlayback?.device.id) {
this.transferPlayback(this.settings.output_device.value);
}

let songData

if (currentPlayback.currently_playing_type === 'track') {
Expand Down
104 changes: 104 additions & 0 deletions DeskThingServer/src/main/handlers/deviceHandler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { sendIpcData } from '..'
import dataListener, { MESSAGE_TYPES } from '../utils/events'
import { join } from 'path'
import * as fs from 'fs'
import * as unzipper from 'unzipper'
import { app, net } from 'electron'
import { handleAdbCommands } from './adbHandler'

export const HandleDeviceData = async (data: any): Promise<void> => {
try {
Expand All @@ -17,3 +22,102 @@ export const HandleDeviceData = async (data: any): Promise<void> => {
dataListener.emit(MESSAGE_TYPES.ERROR, 'HandleDeviceData encountered the error ' + Exception)
}
}
export const HandlePushWebApp = async (
reply: (data: string, payload: any) => void
): Promise<void> => {
try {
const userDataPath = app.getPath('userData')
const extractDir = join(userDataPath, 'webapp')
await handleAdbCommands('shell mount -o remount,rw /')
await handleAdbCommands('shell mv /usr/share/qt-superbird-app/webapp /tmp/webapp-orig')
await handleAdbCommands('shell mv /tmp/webapp-orig /usr/share/qt-superbird-app/')
await handleAdbCommands('shell rm -r /tmp/webapp-orig')
await handleAdbCommands(`push ${extractDir}/ /usr/share/qt-superbird-app/webapp`)
await handleAdbCommands('shell supervisorctl restart chromium')
reply('pushed-staged', { success: true })
} catch (Exception) {
reply('pushed-staged', { success: false, error: Exception })
dataListener.emit(MESSAGE_TYPES.ERROR, 'HandlePushWebApp encountered the error ' + Exception)
}
}

export const HandleWebappZipFromUrl = (
reply: (data: string, payload: any) => void,
zipFileUrl: string
): void => {
const userDataPath = app.getPath('userData')
const extractDir = join(userDataPath, 'webapp')

// Create the extraction directory if it doesn't exist
if (!fs.existsSync(extractDir)) {
fs.mkdirSync(extractDir, { recursive: true })
}

// Download the zip file from the provided URL
const request = net.request(zipFileUrl)

request.on('response', (response) => {
if (response.statusCode === 200) {
const writeStream = fs.createWriteStream(join(extractDir, 'temp.zip'))

response.on('data', (chunk) => {
writeStream.write(chunk)
})

response.on('end', async () => {
writeStream.end()

// Extract the downloaded zip file
try {
await fs
.createReadStream(join(extractDir, 'temp.zip'))
.pipe(unzipper.Extract({ path: extractDir }))
.promise()

// Optionally remove the temporary zip file
fs.unlinkSync(join(extractDir, 'temp.zip'))

console.log(`Successfully extracted ${zipFileUrl} to ${extractDir}`)
dataListener.emit(
MESSAGE_TYPES.LOGGING,
`Successfully extracted ${zipFileUrl} to ${extractDir}`
)

// Notify success to the frontend
reply('zip-extracted', { success: true })
} catch (error) {
console.error('Error extracting zip file:', error)
dataListener.emit(MESSAGE_TYPES.ERROR, `Error extracting zip file: ${error}`)

// Notify failure to the frontend
reply('zip-extracted', { success: false, error: error })
}
})

response.on('error', (error) => {
console.error('Error downloading zip file:', error)
dataListener.emit(MESSAGE_TYPES.ERROR, `Error downloading zip file: ${error}`)

// Notify failure to the frontend
reply('zip-extracted', { success: false, error: error.message })
})
} else {
const errorMessage = `Failed to download zip file: ${response.statusCode}`
console.error(errorMessage)
dataListener.emit(MESSAGE_TYPES.ERROR, errorMessage)

// Notify failure to the frontend
reply('zip-extracted', { success: false, error: errorMessage })
}
})

request.on('error', (error) => {
console.error('Error sending request:', error)
dataListener.emit(MESSAGE_TYPES.ERROR, `Error sending request: ${error}`)

// Notify failure to the frontend
reply('zip-extracted', { success: false, error: error.message })
})

request.end()
}
23 changes: 23 additions & 0 deletions DeskThingServer/src/main/handlers/githubHandler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import axios from 'axios'
import { GithubRelease } from '../types/types'

export async function getReleases(repoUrl: string): Promise<GithubRelease[]> {
try {
// Extract the owner and repo from the URL
const repoMatch = repoUrl.match(/github\.com\/([^/]+)\/([^/]+)/)
if (!repoMatch) {
throw new Error('Invalid GitHub repository URL')
}

const owner = repoMatch[1]
const repo = repoMatch[2]

const apiUrl = `https://api.github.com/repos/${owner}/${repo}/releases`
const response = await axios.get(apiUrl)

return response.data
} catch (error) {
console.error('Error fetching releases:', error)
throw error
}
}
31 changes: 30 additions & 1 deletion DeskThingServer/src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { app, shell, BrowserWindow, ipcMain, Tray, Menu, dialog } from 'electron
import { join } from 'path'
import path from 'path'
import icon from '../../resources/icon.ico?asset'
import { GithubRelease } from './types/types'

let mainWindow: BrowserWindow | null = null
let tray: Tray | null = null
Expand Down Expand Up @@ -108,9 +109,12 @@ async function setupIpcHandlers(): Promise<void> {
)
const { handleAdbCommands } = await import('./handlers/adbHandler')
const { sendData } = await import('./handlers/websocketServer')

const { getReleases } = await import('./handlers/githubHandler')
const { HandleWebappZipFromUrl, HandlePushWebApp } = await import('./handlers/deviceHandler')
const dataListener = (await import('./utils/events')).default
const { MESSAGE_TYPES } = await import('./utils/events')


let connections = 0
ipcMain.on(IPC_CHANNELS.PING, () => console.log('pong'))

Expand Down Expand Up @@ -142,6 +146,23 @@ async function setupIpcHandlers(): Promise<void> {
console.log('SERVER: Return Data after Extraction:', returnData)
event.sender.send('zip-name', returnData)
})
ipcMain.on('extract-webapp-zip', async (event, zipFileUrl) => {
try {
HandleWebappZipFromUrl(event.reply, zipFileUrl)
} catch (error) {
console.error('Error extracting zip file:', error)
event.reply('zip-extracted', { success: false, error: error })
}
})
ipcMain.on('push-staged', async (event) => {
try {
HandlePushWebApp(event.reply)
} catch (error) {
event.reply('pushed-staged', { success: false, error: error })
console.error('Error extracting zip file:', error)
dataListener.emit(MESSAGE_TYPES.ERROR, error)
}
})
ipcMain.on(
IPC_CHANNELS.USER_DATA_RESPONSE,
(event, requestId: string, type: string, ...args: any[]) => {
Expand All @@ -166,6 +187,14 @@ async function setupIpcHandlers(): Promise<void> {
ipcMain.handle('run-adb-command', async (_event, command) => {
return await handleAdbCommands(command)
})
ipcMain.handle('fetch-github-releases', async (_event, url): Promise<GithubRelease[]> => {
try {
return await getReleases(url)
} catch (error) {
dataListener.emit(MESSAGE_TYPES.ERROR, error)
return []
}
})
ipcMain.handle('run-device-command', async (_event, type, command) => {
const data = { app: 'client', type: type, data: JSON.parse(command) }
console.log('Sending data', data)
Expand Down
72 changes: 72 additions & 0 deletions DeskThingServer/src/main/types/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
export interface GithubRelease {
url: string
assets_url: string
upload_url: string
html_url: string
id: number
author: {
login: string
id: number
node_id: string
avatar_url: string
gravatar_id: string
url: string
html_url: string
followers_url: string
following_url: string
gists_url: string
starred_url: string
subscriptions_url: string
organizations_url: string
repos_url: string
events_url: string
received_events_url: string
type: string
site_admin: boolean
}
node_id: string
tag_name: string
target_commitish: string
name: string
draft: boolean
prerelease: boolean
created_at: string
published_at: string
assets: Array<{
url: string
id: number
node_id: string
name: string
label: string
uploader: {
login: string
id: number
node_id: string
avatar_url: string
gravatar_id: string
url: string
html_url: string
followers_url: string
following_url: string
gists_url: string
starred_url: string
subscriptions_url: string
organizations_url: string
repos_url: string
events_url: string
received_events_url: string
type: string
site_admin: boolean
}
content_type: string
state: string
size: number
download_count: number
created_at: string
updated_at: string
browser_download_url: string
}>
tarball_url: string
zipball_url: string
body: string
}
1 change: 1 addition & 0 deletions DeskThingServer/src/preload/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ declare global {
selectZipFile: () => Promise<{ name: string; path: string } | null>
runAdbCommand: (command: string) => Promise<string | null>
runDeviceCommand: (type: string, command: string) => Promise<void>
fetchReleases: (url: string) => Promise<[]>
}
api: unknown // Or define `api` more specifically if you have a shape for it
}
Expand Down
3 changes: 2 additions & 1 deletion DeskThingServer/src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ const api = {
runAdbCommand: (command: string): Promise<string | null> =>
ipcRenderer.invoke('run-adb-command', command),
runDeviceCommand: (type: string, command: string): Promise<string | null> =>
ipcRenderer.invoke('run-device-command', type, command)
ipcRenderer.invoke('run-device-command', type, command),
fetchReleases: (url: string): Promise<[]> => ipcRenderer.invoke('fetch-github-releases', url)
}
// Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise
Expand Down
Loading

0 comments on commit c1d1be2

Please sign in to comment.