Skip to content

Commit

Permalink
Merge pull request #161 from ZorrillosDev/addPortOnLogin
Browse files Browse the repository at this point in the history
feat: added Last key button and local node button to login form
  • Loading branch information
geolffreym authored Sep 8, 2022
2 parents 3048ea4 + 6eda4ca commit 67b7cfe
Show file tree
Hide file tree
Showing 9 changed files with 4,327 additions and 2,832 deletions.
4 changes: 3 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
{
"cSpell.words": [
"IPFS",
"ipns",
"linvodb",
"logplease"
"logplease",
"WATCHIT"
]
}
6,957 changes: 4,171 additions & 2,786 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 2 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "watchit",
"author": "ZorrillosDev",
"version": "0.3.5-alpha.1",
"version": "0.3.6-alpha.1",
"private": true,
"main": "./src/main/index.js",
"description": "Open movies everywhere",
Expand Down Expand Up @@ -79,8 +79,7 @@
"package.json"
],
"dmg": {
"contents":
[
"contents": [
{
"x": 130,
"y": 220
Expand Down
9 changes: 6 additions & 3 deletions src/main/core/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,20 @@
const log = require('logplease').create('CORE')
const Node = require('./node')
const Ingest = require('./ingest')
// const BroadCast = require('./broadcast')
const key = require('./key')

module.exports = (ipcMain, runtime = 'node') => {
let nodeConf = { }
let nodeConf = {}
const keyFile = key.readFromStorage()
// Check if user added local node port
const node = keyFile && 'node' in keyFile ? keyFile.node : null

if (!Object.is(runtime, 'web')) {
const { ROOT_ORBIT_DIR } = require('./settings')
nodeConf = Object.assign({ directory: ROOT_ORBIT_DIR }, nodeConf)
}

const orbit = Node.getInstance({ orbit: nodeConf })
const orbit = Node.getInstance({ orbit: nodeConf, ipfs: { node } })
const ingest = Ingest.getInstance(orbit)

/**
Expand Down
34 changes: 25 additions & 9 deletions src/main/core/ipfs/node/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,17 @@ const getPort = require('get-port')
const Ctl = require('ipfsd-ctl')
const defaultConf = require('./settings')
const log = require('logplease').create('IPFS')
const IPFSClient = require('ipfs-http-client')

// Path settings and util helper lib
const { removeFiles } = require('../../utils')
const { ROOT_IPFS_DIR } = require('../../settings')

const DEFAULT_LOOPBACK = '127.0.0.1'
const RETRY_GRACE = 20 * 1000
const DEFAULT_API_PORT = 5001
const DEFAULT_GATEWAY_PORT = 8080
const KILL_TIMEOUT = 15 * 1000
const DEFAULT_API_PORT = 6002
const DEFAULT_GATEWAY_PORT = 9090
const DEFAULT_SWARM_TCP = 4010
const DEFAULT_SWARM_WS = 4011
const resolveIpfsPaths = () => require('go-ipfs').path()
Expand All @@ -23,7 +25,9 @@ const forceKill = async (isInstance) => {
await isInstance.stop()
log.warn('Cleaning bad repo')
await removeFiles(ROOT_IPFS_DIR)
}; const initIpfsNode = async (isInstance) => {
}

const initIpfsNode = async (isInstance) => {
// Check if running time dir exists
log.warn('Starting node')
try {
Expand All @@ -34,7 +38,19 @@ const forceKill = async (isInstance) => {
}

return isInstance.start()
}; const ipfsFactory = async (conf = {}) => {
}

const ipfsFactory = async (conf = {}) => {
// Link to current local node
if ('node' in conf) {
log.info('Using provided node on port:', conf.node)
return IPFSClient.create({
host: DEFAULT_LOOPBACK,
port: conf.node,
protocol: 'http'
})
}

// Find available ports to avoid conflict
const [api, gateway, swarmTCP, swarmWS] = await Promise.all([
getPort({ port: DEFAULT_API_PORT }),
Expand All @@ -57,13 +73,13 @@ const forceKill = async (isInstance) => {
},
...conf
},
ipfsHttpModule: require('ipfs-http-client'),
ipfsHttpModule: IPFSClient,
ipfsBin: resolveIpfsPaths(),
forceKill: true,
disposable: false,
forceKillTimeout: KILL_TIMEOUT,
args: ['--enable-pubsub-experiment'],
forceKill: true,
remote: false,
forceKillTimeout: KILL_TIMEOUT,
type: 'go'
})

Expand All @@ -87,15 +103,15 @@ const forceKill = async (isInstance) => {
} catch (e) {
// Avoid throw default error
log.error('Fail on start')
await forceKill(isInstance)
return false
}
await forceKill(isInstance)

const ipfsApi = isInstance?.api
const id = ipfsApi.peerId
ipfsApi.kill = async () => isInstance.stop()
log.info(`Started ${isInstance.started}`)
log.info('Running ipfs id', id.id)
ipfsApi.kill = async () => isInstance.stop()

return ipfsApi
}
Expand Down
10 changes: 6 additions & 4 deletions src/main/core/node.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ module.exports = class Node extends EventEmitter {
}

async getIngestKey () {
return await this.resolveKey(
return this.resolveKey(
this.rawIngestKey
)
}
Expand Down Expand Up @@ -125,7 +125,7 @@ module.exports = class Node extends EventEmitter {
}

/**
* Opem orbit address and set events listeners
* Open orbit address and set events listeners
* @param key: orbit address
* @param res: callback
*/
Expand Down Expand Up @@ -188,10 +188,12 @@ module.exports = class Node extends EventEmitter {
const raw = await this.getIngestKey()
if (!raw) return false // Avoid move forward
const address = this.sanitizeKey(raw)

// Get orbit instance and next line connect providers
this.orbit = await this.instanceOB()
log.warn('Sanitized key:', address)
this.emit('node-step', 'Connecting')

await this.run(address, res) // Wait for orbit to open db
this.emit('node-raised') // When all ready to handle orbit
await provider.findProv(this.node, raw)
Expand All @@ -202,7 +204,7 @@ module.exports = class Node extends EventEmitter {
*/
instanceOB () {
return (this.orbit && Promise.resolve(this.orbit)) ||
OrbitDB.createInstance(this.node, this.conf.orbit)
OrbitDB.createInstance(this.node, this.conf.orbit)
}

/**
Expand Down Expand Up @@ -256,7 +258,7 @@ module.exports = class Node extends EventEmitter {
}
}

if (this.node) {
if (this.node && this.node?.kill) {
log.warn('Killing Nodes')
await this.node.kill().catch(
() => log.error('Fail trying to stop node')
Expand Down
2 changes: 1 addition & 1 deletion src/render/core/app/components/Input/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ const Input = (props) => {
}

return (
<InputWrapper>
<InputWrapper className='input-wrapper'>
{props.icon && <InputIcon className={props.icon} />}
<InputElement
value={value}
Expand Down
129 changes: 108 additions & 21 deletions src/render/core/app/components/Login/index.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
/* global FormData */
import React, { useState } from 'react'
import React, { useState, useCallback } from 'react'
import styled from 'styled-components'
import Alert from '@components/Alert/'
import Input from '@components/Input/'
Expand All @@ -8,42 +7,43 @@ import Background from '@components/Background/'
import { Key as key } from '@main/bridge'
import setting from '@settings'

const pb = process.env.WATCHIT_PUBLIC_KEY
const runtime = process.env.RUNTIME
const isWeb = runtime === 'web'

const LoginForm = () => {
const fields = new FormData()
const [submitted, setSubmitted] = useState(false)
const [error, setError] = useState(false)
const [ingest, setValue] = useState('')
const [node, setNode] = useState('')
const [showLocalNode, setShowLocalNode] = useState(false)

const handleInput = (event) => {
// If the input fields were directly within this
// Set input in formData
fields.set(
event.target.name,
event.target.value
)
}

const handleSubmit = (e) => {
const handleSubmit = useCallback((e) => {
// Avoid trigger default event
e.preventDefault()
// Set first state
setError(false)
setSubmitted(true)

const pb = fields.get('public')
// This validation should be skip
const dataToStore = {
...node && { node },
...{ ingest }
}

// This validation should be skip because we can use orbit or ipns address
// Check if stored key its valid
// if (!key.isValidKey(pb)) {
// setError('Invalid Key')
// return setSubmitted(false)
// }

// Write public key
key.generateKey({ ingest: pb })
key.generateKey(dataToStore)
setTimeout(() => {
// Set first state
window.location.href = '#/app/movies'
}, 2000)
}
}, [node, ingest])

return (
<LoginWrapper>
Expand All @@ -52,16 +52,56 @@ const LoginForm = () => {
<form onSubmit={handleSubmit} autoComplete='new-password'>
<FormRow>
<Input
value={ingest}
placeholder='Public Key'
name='public' required
onChange={handleInput}
onInput={(e) => setValue(e.target.value)}
/>
</FormRow>

<FormRow>
<Button clicked={submitted} type='submit'>
<span>Connect</span>
</Button>
<ButtonsContainer>
<LoginButtonContainer>
<Button clicked={submitted} type='submit'>
<span>Connect</span>
</Button>
</LoginButtonContainer>
<SmallButtonContainer size={isWeb ? '50%' : null} onClick={() => setValue(pb)}>
<Button clicked={submitted} type='button'>
<span>Last Key</span>
</Button>
</SmallButtonContainer>
{!isWeb
? (
<SmallButtonContainer>
{
showLocalNode
? (
<>
<Input
placeholder='Port'
name='node_port'
type='number'
value={node}
onChange={(e) => setNode(e.target.value)}
/>
<div className='cancel-button' onClick={() => setShowLocalNode(false)}>
<i className='icon-cross white-text' />
</div>
</>
)
: (
<div onClick={() => setShowLocalNode(true)}>
<Button clicked={submitted} type='button'>
<span>Local Node</span>
</Button>
</div>
)
}
</SmallButtonContainer>
)
: <></>}
</ButtonsContainer>
</FormRow>

{
Expand Down Expand Up @@ -112,6 +152,53 @@ const LoginWrapper = styled.div`

const FormRow = styled.div`
margin-bottom: 20px;
display: flex;
align-items: center;
justify-content: space-between;
`

const ButtonsContainer = styled.div`
width: 100%;
display: flex;
flex-wrap: wrap;
grid-gap: 1rem;
`

const LoginButtonContainer = styled.div`
width: calc(50% - 1rem);
@media (max-width: 500px) {
width: 100%;
}
`

const SmallButtonContainer = styled.div`
width: ${props => `calc(${props.size ? props.size : '25%'} - 0.5rem)`};
position: relative;
.input-wrapper {
height: 36px;
input {
height: 36px;
}
}
.cancel-button {
width: 2rem;
height: 100%;
position: absolute;
right: 0;
top: 0;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
}
@media (max-width: 500px) {
width: 100%;
}
`

export default React.memo(LoginForm)
9 changes: 5 additions & 4 deletions src/render/core/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@ export default {
// 'https://vps1.phillm.net',
// 'https://vps2.phillm.net',
// 'https://vps3.phillm.net',
'https://watchit.mypinata.cloud',
'https://ipfs.infura.io',
// 'https://gateway.pinata.cloud',
// 'https://watchit.mypinata.cloud',
'https://ipfs.filebase.io',
'https://gateway.ipfs.io',
'https://ipfs.io',
...process.env.RUNTIME !== 'web'
? ['http://localhost:9090']
? ['http://localhost:8080']
: []
],
subs: {
Expand Down

0 comments on commit 67b7cfe

Please sign in to comment.