Formatting update

This commit is contained in:
uonai 2020-07-08 22:19:08 -05:00
parent c28b41f8b3
commit 770ea69f06
9 changed files with 150 additions and 342 deletions

1
.gitignore vendored
View File

@ -5,7 +5,6 @@ DS_STORE
package-lock.json
node_modules
dist
nodedistribution
/**/*/package-lock.json
/**/*/.DS_STORE

View File

@ -125,7 +125,7 @@ export default class SidebarFileStorageDeal extends React.Component {
return (
<React.Fragment>
<System.P style={{ fontFamily: 'inter-semi-bold' }}>
<System.P style={{ fontFamily: Constants.font.semiBold }}>
Upload a file to the network
</System.P>
<input

View File

@ -1,188 +0,0 @@
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./electron/main.js");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./electron sync recursive":
/*!***********************!*\
!*** ./electron sync ***!
\***********************/
/*! no static exports found */
/***/ (function(module, exports) {
function webpackEmptyContext(req) {
var e = new Error("Cannot find module '" + req + "'");
e.code = 'MODULE_NOT_FOUND';
throw e;
}
webpackEmptyContext.keys = function() { return []; };
webpackEmptyContext.resolve = webpackEmptyContext;
module.exports = webpackEmptyContext;
webpackEmptyContext.id = "./electron sync recursive";
/***/ }),
/***/ "./electron/main.js":
/*!**************************!*\
!*** ./electron/main.js ***!
\**************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(__dirname) {// Modules to control application life and create native browser window
var _require = __webpack_require__(/*! electron */ "electron"),
app = _require.app,
BrowserWindow = _require.BrowserWindow;
var path = __webpack_require__(/*! path */ "path"); // const { fork } = require("child_process");
// const ps = fork(path.join(__dirname, "..", "index.js"));
function createWindow() {
// Create the browser window.
var mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
nodeIntegration: true
}
}); // Open the DevTools.
mainWindow.webContents.openDevTools(); // and load the index.html of the app.
mainWindow.loadURL("http://localhost:1337");
console.log("window created");
__webpack_require__("./electron sync recursive")(path.join(__dirname, "../nodedistribution/", "main.js"));
} // This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(function () {
createWindow();
app.on("activate", function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});
}); // Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on("window-all-closed", function () {
if (process.platform !== "darwin") app.quit();
}); // In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
/* WEBPACK VAR INJECTION */}.call(this, "/"))
/***/ }),
/***/ "electron":
/*!***************************!*\
!*** external "electron" ***!
\***************************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = require("electron");
/***/ }),
/***/ "path":
/*!***********************!*\
!*** external "path" ***!
\***********************/
/*! no static exports found */
/***/ (function(module, exports) {
module.exports = require("path");
/***/ })
/******/ });
//# sourceMappingURL=main.js.map

File diff suppressed because one or more lines are too long

View File

@ -15,6 +15,4 @@ require('@babel/register')({
ignore: ['node_modules', '.next'],
});
console.log('index.js ran');
module.exports = require('./server.js');
console.log('server.js ran');

View File

@ -1,30 +1,30 @@
import * as Constants from './constants';
import * as Constants from "./constants";
import FS from 'fs-extra';
import FS from "fs-extra";
export const resetFileSystem = async () => {
console.log('[ prototype ] deleting old token and library data ');
console.log("[ prototype ] deleting old token and library data ");
if (FS.existsSync(`./.data`)) {
FS.removeSync('./.data', { recursive: true });
FS.removeSync("./.data", { recursive: true });
}
console.log('[ prototype ] deleting old avatar data ');
console.log("[ prototype ] deleting old avatar data ");
if (FS.existsSync(Constants.AVATAR_STORAGE_URL)) {
FS.removeSync(Constants.AVATAR_STORAGE_URL, { recursive: true });
}
console.log('[ prototype ] deleting old file data ');
console.log("[ prototype ] deleting old file data ");
if (FS.existsSync(Constants.FILE_STORAGE_URL)) {
FS.removeSync(Constants.FILE_STORAGE_URL, { recursive: true });
}
console.log('[ prototype ] creating new avatar folder ');
console.log("[ prototype ] creating new avatar folder ");
FS.mkdirSync(Constants.AVATAR_STORAGE_URL, { recursive: true });
FS.writeFileSync(`${Constants.AVATAR_STORAGE_URL}.gitkeep`, '');
FS.writeFileSync(`${Constants.AVATAR_STORAGE_URL}.gitkeep`, "");
console.log('[ prototype ] creating new local file folder ');
console.log("[ prototype ] creating new local file folder ");
FS.mkdirSync(Constants.FILE_STORAGE_URL, { recursive: true });
FS.writeFileSync(`${Constants.FILE_STORAGE_URL}.gitkeep`, '');
FS.writeFileSync(`${Constants.FILE_STORAGE_URL}.gitkeep`, "");
return true;
};
@ -66,7 +66,7 @@ export const emitState = async ({ state, client, PG }) => {
});
if (client) {
client.send(JSON.stringify({ action: 'UPDATE_VIEWER', data }));
client.send(JSON.stringify({ action: "UPDATE_VIEWER", data }));
}
return data;
@ -74,18 +74,18 @@ export const emitState = async ({ state, client, PG }) => {
export const getFileName = (s) => {
let target = s;
if (target.endsWith('/')) {
if (target.endsWith("/")) {
target = target.substring(0, target.length - 1);
}
return target.substr(target.lastIndexOf('/') + 1);
return target.substr(target.lastIndexOf("/") + 1);
};
export const createFile = ({ id, data }) => {
return {
decorator: 'FILE',
decorator: "FILE",
id: id,
icon: 'PNG',
icon: "PNG",
file: getFileName(id),
miner: null,
job_id: null,
@ -103,10 +103,10 @@ export const createFile = ({ id, data }) => {
export const createFolder = ({ id }) => {
return {
decorator: 'FOLDER',
decorator: "FOLDER",
id,
folderId: id,
icon: 'FOLDER',
icon: "FOLDER",
file: getFileName(id),
name: getFileName(id),
pageTitle: null,
@ -131,7 +131,7 @@ export const refreshLibrary = async ({ state, PG, FFS }) => {
if (state.library[i].children[j].job_id) {
if (state.library[i].children[j].storage_status === 1) {
console.log(
'[ prototype ] update file',
"[ prototype ] update file",
state.library[i].children[j]
);
state.library[i].children[j].storage_status = 2;
@ -140,10 +140,10 @@ export const refreshLibrary = async ({ state, PG, FFS }) => {
}
PG.ffs.watchJobs((job) => {
console.log('[ prototype ] job status', job.status);
console.log("[ prototype ] job status", job.status);
if (job.status === FFS.JobStatus.JOB_STATUS_SUCCESS) {
console.log(
'[ prototype ] update file',
"[ prototype ] update file",
state.library[i].children[j]
);
state.library[i].children[j].storage_status = 6;
@ -156,7 +156,7 @@ export const refreshLibrary = async ({ state, PG, FFS }) => {
if (write) {
FS.writeFileSync(
'./.data/library.json',
"./.data/library.json",
JSON.stringify({ library: state.library })
);
}

View File

@ -1,39 +1,39 @@
import * as React from 'react';
import * as NavigationData from '~/common/navigation-data';
import * as Actions from '~/common/actions';
import * as State from '~/common/state';
import * as React from "react";
import * as NavigationData from "~/common/navigation-data";
import * as Actions from "~/common/actions";
import * as State from "~/common/state";
import SceneDataTransfer from '~/scenes/SceneDataTransfer';
import SceneDeals from '~/scenes/SceneDeals';
import SceneEditAccount from '~/scenes/SceneEditAccount';
import SceneFile from '~/scenes/SceneFile';
import SceneFilesFolder from '~/scenes/SceneFilesFolder';
import SceneHome from '~/scenes/SceneHome';
import SceneLogs from '~/scenes/SceneLogs';
import SceneMiners from '~/scenes/SceneMiners';
import ScenePaymentChannels from '~/scenes/ScenePaymentChannels';
import ScenePeers from '~/scenes/ScenePeers';
import SceneSettings from '~/scenes/SceneSettings';
import SceneStats from '~/scenes/SceneStats';
import SceneStatus from '~/scenes/SceneStatus';
import SceneStorageMarket from '~/scenes/SceneStorageMarket';
import SceneWallet from '~/scenes/SceneWallet';
import SceneDataTransfer from "~/scenes/SceneDataTransfer";
import SceneDeals from "~/scenes/SceneDeals";
import SceneEditAccount from "~/scenes/SceneEditAccount";
import SceneFile from "~/scenes/SceneFile";
import SceneFilesFolder from "~/scenes/SceneFilesFolder";
import SceneHome from "~/scenes/SceneHome";
import SceneLogs from "~/scenes/SceneLogs";
import SceneMiners from "~/scenes/SceneMiners";
import ScenePaymentChannels from "~/scenes/ScenePaymentChannels";
import ScenePeers from "~/scenes/ScenePeers";
import SceneSettings from "~/scenes/SceneSettings";
import SceneStats from "~/scenes/SceneStats";
import SceneStatus from "~/scenes/SceneStatus";
import SceneStorageMarket from "~/scenes/SceneStorageMarket";
import SceneWallet from "~/scenes/SceneWallet";
import SidebarCreateWalletAddress from '~/components/sidebars/SidebarCreateWalletAddress';
import SidebarDeleteWalletAddress from '~/components/sidebars/SidebarDeleteWalletAddress';
import SidebarWalletSendFunds from '~/components/sidebars/SidebarWalletSendFunds';
import SidebarFileStorageDeal from '~/components/sidebars/SidebarFileStorageDeal';
import SidebarFileRetrievalDeal from '~/components/sidebars/SidebarFileRetrievalDeal';
import SidebarCreatePaymentChannel from '~/components/sidebars/SidebarCreatePaymentChannel';
import SidebarAddMiner from '~/components/sidebars/SidebarAddMiner';
import SidebarAddPeer from '~/components/sidebars/SidebarAddPeer';
import SidebarNotifications from '~/components/sidebars/SidebarNotifications';
import SidebarRedeemPaymentChannel from '~/components/sidebars/SidebarRedeemPaymentChannel';
import SidebarCreateWalletAddress from "~/components/sidebars/SidebarCreateWalletAddress";
import SidebarDeleteWalletAddress from "~/components/sidebars/SidebarDeleteWalletAddress";
import SidebarWalletSendFunds from "~/components/sidebars/SidebarWalletSendFunds";
import SidebarFileStorageDeal from "~/components/sidebars/SidebarFileStorageDeal";
import SidebarFileRetrievalDeal from "~/components/sidebars/SidebarFileRetrievalDeal";
import SidebarCreatePaymentChannel from "~/components/sidebars/SidebarCreatePaymentChannel";
import SidebarAddMiner from "~/components/sidebars/SidebarAddMiner";
import SidebarAddPeer from "~/components/sidebars/SidebarAddPeer";
import SidebarNotifications from "~/components/sidebars/SidebarNotifications";
import SidebarRedeemPaymentChannel from "~/components/sidebars/SidebarRedeemPaymentChannel";
import ApplicationNavigation from '~/components/core/ApplicationNavigation';
import ApplicationHeader from '~/components/core/ApplicationHeader';
import ApplicationLayout from '~/components/core/ApplicationLayout';
import WebsitePrototypeWrapper from '~/components/core/WebsitePrototypeWrapper';
import ApplicationNavigation from "~/components/core/ApplicationNavigation";
import ApplicationHeader from "~/components/core/ApplicationHeader";
import ApplicationLayout from "~/components/core/ApplicationLayout";
import WebsitePrototypeWrapper from "~/components/core/WebsitePrototypeWrapper";
const getCurrentNavigationStateById = (navigation, targetId) => {
let target = null;
@ -82,7 +82,7 @@ export default class IndexPage extends React.Component {
currentIndex: 0,
data: null,
selected: {
address: '',
address: "",
},
viewer: State.getInitialState(this.props),
sidebar: null,
@ -93,36 +93,36 @@ export default class IndexPage extends React.Component {
this._socket = new WebSocket(`ws://localhost:${this.props.wsPort}`);
this._socket.onmessage = (m) => {
console.log(m);
if (m.type === 'message') {
if (m.type === "message") {
const parsed = JSON.parse(m.data);
if (parsed.action === 'UPDATE_VIEWER') {
if (parsed.action === "UPDATE_VIEWER") {
this.rehydrate({ data: parsed.data });
}
}
};
window.addEventListener('dragenter', this._handleDragEnter);
window.addEventListener('dragleave', this._handleDragLeave);
window.addEventListener('dragover', this._handleDragOver);
window.addEventListener('drop', this._handleDrop);
window.addEventListener("dragenter", this._handleDragEnter);
window.addEventListener("dragleave", this._handleDragLeave);
window.addEventListener("dragover", this._handleDragOver);
window.addEventListener("drop", this._handleDrop);
}
componentWillUnmount() {
window.removeEventListener('dragenter', this._handleDragEnter);
window.removeEventListener('dragleave', this._handleDragLeave);
window.removeEventListener('dragover', this._handleDragOver);
window.removeEventListener('drop', this._handleDrop);
window.removeEventListener("dragenter", this._handleDragEnter);
window.removeEventListener("dragleave", this._handleDragLeave);
window.removeEventListener("dragover", this._handleDragOver);
window.removeEventListener("drop", this._handleDrop);
}
_handleSetFile = async ({ file }) => {
let data = new FormData();
data.append('image', file);
data.append("image", file);
const options = {
method: 'POST',
method: "POST",
headers: {
Accept: 'application/json',
Accept: "application/json",
},
body: data,
};
@ -137,17 +137,17 @@ export default class IndexPage extends React.Component {
_handleDragEnter = (e) => {
// TODO(jim): Styles.
console.log('dragenter', e);
console.log("dragenter", e);
};
_handleDragLeave = (e) => {
// TODO(jim): Styles.
console.log('dragleave', e);
console.log("dragleave", e);
};
_handleDragOver = (e) => {
e.preventDefault();
console.log('dragover', e);
console.log("dragover", e);
};
_handleDrop = async (e) => {
@ -155,7 +155,7 @@ export default class IndexPage extends React.Component {
if (e.dataTransfer.items) {
for (var i = 0; i < e.dataTransfer.items.length; i++) {
if (e.dataTransfer.items[i].kind === 'file') {
if (e.dataTransfer.items[i].kind === "file") {
var file = e.dataTransfer.items[i].getAsFile();
console.log(file.name);
await this._handleSetFile({ file });
@ -164,7 +164,7 @@ export default class IndexPage extends React.Component {
}
}
this._handleAction({ type: 'SIDEBAR', value: 'SIDEBAR_FILE_STORAGE_DEAL' });
this._handleAction({ type: "SIDEBAR", value: "SIDEBAR_FILE_STORAGE_DEAL" });
};
rehydrate = async ({ data }) => {
@ -173,11 +173,11 @@ export default class IndexPage extends React.Component {
_handleSubmit = async (data) => {
if (this.props.production) {
alert('TODO');
alert("TODO");
return this._handleDismissSidebar();
}
if (data.type === 'CREATE_WALLET_ADDRESS') {
if (data.type === "CREATE_WALLET_ADDRESS") {
const address = await Actions.createWalletAddress({
name: data.name,
type: data.wallet_type,
@ -185,7 +185,7 @@ export default class IndexPage extends React.Component {
});
}
if (data.type === 'SEND_WALLET_ADDRESS_FILECOIN') {
if (data.type === "SEND_WALLET_ADDRESS_FILECOIN") {
const response = await Actions.sendWalletAddressFilecoin({
source: data.source,
target: data.target,
@ -217,19 +217,19 @@ export default class IndexPage extends React.Component {
};
_handleAction = (options) => {
if (options.type === 'NAVIGATE') {
if (options.type === "NAVIGATE") {
return this._handleNavigateTo({ id: options.value }, options.data);
}
if (options.type === 'ACTION') {
if (options.type === "ACTION") {
return alert(JSON.stringify(options));
}
if (options.type === 'DOWNLOAD') {
if (options.type === "DOWNLOAD") {
return alert(JSON.stringify(options));
}
if (options.type === 'SIDEBAR') {
if (options.type === "SIDEBAR") {
return this.setState({ sidebar: this.sidebars[options.value] });
}
@ -389,8 +389,8 @@ export default class IndexPage extends React.Component {
}
const title = `Prototype 0.0.1 : ${current.target.pageTitle}`;
const description = 'This is an early preview.';
const url = 'https://fps.onrender.com/v1';
const description = "This is an early preview.";
const url = "https://fps.onrender.com/v1";
return (
<React.Fragment>

View File

@ -1,14 +1,14 @@
import * as React from 'react';
import * as Strings from '~/common/strings';
import * as Constants from '~/common/constants';
import * as Fixtures from '~/common/fixtures';
import * as System from '~/components/system';
import * as SVG from '~/components/system/svg';
import * as React from "react";
import * as Strings from "~/common/strings";
import * as Constants from "~/common/constants";
import * as Fixtures from "~/common/fixtures";
import * as System from "~/components/system";
import * as SVG from "~/components/system/svg";
import { css } from '@emotion/react';
import { css } from "@emotion/react";
import Section from '~/components/core/Section';
import ScenePage from '~/components/core/ScenePage';
import Section from "~/components/core/Section";
import ScenePage from "~/components/core/ScenePage";
const STYLES_FLEX = css`
display: flex;
@ -72,7 +72,7 @@ const STYLES_BOTTOM = css`
`;
const STYLES_PATH = css`
font-family: 'mono';
font-family: "mono";
color: ${Constants.system.white};
font-size: 12px;
text-transform: uppercase;
@ -90,7 +90,7 @@ const STYLES_ITEM = css`
justify-content: center;
font-size: 12px;
letter-spacing: 0.2px;
font-family: 'inter-semi-bold';
font-family: "inter-semi-bold";
transition: 200ms ease all;
cursor: pointer;
background-color: ${Constants.system.brand};

112
server.js
View File

@ -1,45 +1,45 @@
import * as Middleware from './common/middleware';
import * as Strings from './common/strings';
import * as Utilities from './node_common/utilities';
import * as Constants from './node_common/constants';
import * as Middleware from "./common/middleware";
import * as Strings from "./common/strings";
import * as Utilities from "./node_common/utilities";
import * as Constants from "./node_common/constants";
import { createPow, ffs } from '@textile/powergate-client';
import { createPow, ffs } from "@textile/powergate-client";
// NOTE(jim):
// https://github.com/textileio/js-powergate-client
const PowerGate = createPow({ host: Constants.POWERGATE_HOST });
import FS from 'fs-extra';
import WebSocketServer from 'ws';
import express from 'express';
import formidable from 'formidable';
import next from 'next';
import bodyParser from 'body-parser';
import compression from 'compression';
import { v4 as uuid } from 'uuid';
import FS from "fs-extra";
import WebSocketServer from "ws";
import express from "express";
import formidable from "formidable";
import next from "next";
import bodyParser from "body-parser";
import compression from "compression";
import { v4 as uuid } from "uuid";
// TODO(jim): Support multiple desktop applications.
let client = null;
let state = null;
const production = process.env.NODE_ENV === 'production';
const production = process.env.NODE_ENV === "production";
const port = process.env.PORT || 1337;
const wsPort = process.env.WS_PORT || 2448;
const app = next({ dev: !production, dir: __dirname, quiet: false });
const nextRequestHandler = app.getRequestHandler();
const path = require('path');
const path = require("path");
const setIntervalViewerUpdatesUnsafe = async () => {
if (client) {
try {
console.log('[ prototype ] polling: new viewer state.');
console.log("[ prototype ] polling: new viewer state.");
state = await Utilities.emitState({
state,
client,
PG: PowerGate,
});
console.log('[ prototype ] polling: new library state.');
console.log("[ prototype ] polling: new library state.");
state = await Utilities.refreshLibrary({
state,
PG: PowerGate,
@ -54,7 +54,7 @@ const setIntervalViewerUpdatesUnsafe = async () => {
};
app.prepare().then(async () => {
console.log('[ prototype ] initializing ');
console.log("[ prototype ] initializing ");
state = {
production,
@ -77,18 +77,18 @@ app.prepare().then(async () => {
const updates = await Utilities.refresh({ PG: PowerGate });
state = await Utilities.updateStateData(state, updates);
console.log('[ prototype ] updated without token');
console.log("[ prototype ] updated without token");
// NOTE(jim): This is a configuration folder with all of the client tokens.
// TODO(jim): Unnecessary if we use a local and remote postgres.
const dirnameData = path.join(__dirname, '/.data');
const dirnameData = path.join(__dirname, "/.data");
if (!FS.existsSync(dirnameData)) {
FS.mkdirSync(dirnameData, { recursive: true });
}
// NOTE(jim): This will create a token for authentication with powergate.
// TODO(jim): Roll this up into Postgres instead.
const dirnamePowergate = path.join(__dirname, '/.data/powergate-token');
const dirnamePowergate = path.join(__dirname, "/.data/powergate-token");
if (!FS.existsSync(dirnamePowergate)) {
const FFS = await PowerGate.ffs.create();
state.token = FFS.token ? FFS.token : null;
@ -98,11 +98,11 @@ app.prepare().then(async () => {
FS.writeFileSync(dirnamePowergate, state.token);
}
} else {
state.token = FS.readFileSync(dirnamePowergate, 'utf8');
state.token = FS.readFileSync(dirnamePowergate, "utf8");
}
if (state.token) {
console.log('[ prototype ] powergate token:', state.token);
console.log("[ prototype ] powergate token:", state.token);
PowerGate.setToken(state.token);
}
@ -110,19 +110,19 @@ app.prepare().then(async () => {
PG: PowerGate,
});
state = await Utilities.updateStateData(state, tokenUpdates);
console.log('[ prototype ] updated with token');
console.log("[ prototype ] updated with token");
// NOTE(jim): Local library retrieval or creation
// TODO(jim): Needs to support nested folders in the future.
// TODO(jim): May consider a move to buckets.
const dirnameLibrary = path.join(__dirname, '/.data/library.json');
const dirnameLibrary = path.join(__dirname, "/.data/library.json");
if (!FS.existsSync(dirnameLibrary)) {
const librarySchema = {
library: [
{
...Utilities.createFolder({ id: Constants.FILE_STORAGE_URL }),
file: 'Files',
name: 'Files',
file: "Files",
name: "Files",
},
],
};
@ -130,7 +130,7 @@ app.prepare().then(async () => {
FS.writeFileSync(dirnameLibrary, JSON.stringify(librarySchema));
state.library = librarySchema.library;
} else {
const parsedLibrary = FS.readFileSync(dirnameLibrary, 'utf8');
const parsedLibrary = FS.readFileSync(dirnameLibrary, "utf8");
state.library = JSON.parse(parsedLibrary).library;
}
@ -138,7 +138,7 @@ app.prepare().then(async () => {
// TODO(jim): Move this to postgres later.
const dirnameLocalSettings = path.join(
__dirname,
'/.data/local-settings.json'
"/.data/local-settings.json"
);
if (!FS.existsSync(dirnameLocalSettings)) {
const localSettingsSchema = {
@ -155,33 +155,33 @@ app.prepare().then(async () => {
);
state.local = localSettingsSchema.local;
} else {
const parsedLocal = FS.readFileSync(dirnameLocalSettings, 'utf8');
const parsedLocal = FS.readFileSync(dirnameLocalSettings, "utf8");
state.local = JSON.parse(parsedLocal).local;
}
} catch (e) {
console.log(e);
console.log('[ prototype ] "/" -- WILL REDIRECT TO /SYSTEM ');
console.log(
'[ prototype ] SLATE WILL NOT RUN LOCALLY UNTIL YOU HAVE '
"[ prototype ] SLATE WILL NOT RUN LOCALLY UNTIL YOU HAVE "
);
console.log('[ prototype ] PROPERLY CONFIGURED POWERGATE AND ');
console.log("[ prototype ] PROPERLY CONFIGURED POWERGATE AND ");
console.log(
'[ prototype ] CONNECTED TO THE FILECOIN NETWORK (DEVNET/TESTNET) '
"[ prototype ] CONNECTED TO THE FILECOIN NETWORK (DEVNET/TESTNET) "
);
}
const server = express();
const WSS = new WebSocketServer.Server({ port: wsPort });
WSS.on('connection', (s) => {
WSS.on("connection", (s) => {
// TODO(jim): Suppport more than one client.
client = s;
s.on('close', function () {
s.send(JSON.stringify({ action: null, data: 'closed' }));
s.on("close", function () {
s.send(JSON.stringify({ action: null, data: "closed" }));
});
s.send(JSON.stringify({ action: null, data: 'connected' }));
s.send(JSON.stringify({ action: null, data: "connected" }));
});
if (production) {
@ -189,7 +189,7 @@ app.prepare().then(async () => {
}
server.use(Middleware.CORS);
server.use('/public', express.static('public'));
server.use("/public", express.static("public"));
server.use(bodyParser.json());
server.use(
bodyParser.urlencoded({
@ -197,7 +197,7 @@ app.prepare().then(async () => {
})
);
server.post('/_/viewer', async (req, res) => {
server.post("/_/viewer", async (req, res) => {
let data = state;
if (!production) {
@ -214,7 +214,7 @@ app.prepare().then(async () => {
return res.status(200).send({ success: true, data });
});
server.post('/_/deals/storage', async (req, res) => {
server.post("/_/deals/storage", async (req, res) => {
if (Strings.isEmpty(req.body.src)) {
return res.status(500).send({ success: false });
}
@ -239,7 +239,7 @@ app.prepare().then(async () => {
// NOTE(jim): Writes the updated deal state.
if (write) {
const dirnameLibrary = path.join(__dirname, '/.data/library.json');
const dirnameLibrary = path.join(__dirname, "/.data/library.json");
FS.writeFileSync(
dirnameLibrary,
JSON.stringify({ library: state.library })
@ -250,7 +250,7 @@ app.prepare().then(async () => {
return res.status(200).send({ success: true, cid, jobId });
});
server.post('/_/storage/:file', async (req, res) => {
server.post("/_/storage/:file", async (req, res) => {
const form = formidable({
multiples: true,
uploadDir: Constants.FILE_STORAGE_URL,
@ -262,10 +262,10 @@ app.prepare().then(async () => {
} else {
// TODO(jim): Need to support other file types.
if (!files.image) {
console.error('[ prototype ] File type unspported', files);
console.error("[ prototype ] File type unspported", files);
return res
.status(500)
.send({ error: 'File type unsupported', files });
.send({ error: "File type unsupported", files });
}
const newPath = form.uploadDir + req.params.file;
@ -288,7 +288,7 @@ app.prepare().then(async () => {
// NOTE(jim): Writes the added file.
if (pushed) {
const dirnameLibrary = path.join(__dirname, '/.data/library.json');
const dirnameLibrary = path.join(__dirname, "/.data/library.json");
FS.writeFileSync(
dirnameLibrary,
JSON.stringify({ library: state.library })
@ -306,7 +306,7 @@ app.prepare().then(async () => {
});
});
server.post('/_/upload/avatar', async (req, res) => {
server.post("/_/upload/avatar", async (req, res) => {
const form = formidable({
multiples: true,
uploadDir: Constants.AVATAR_STORAGE_URL,
@ -324,7 +324,7 @@ app.prepare().then(async () => {
state.local.photo = __dirname + `/static/system/${newName}`;
const dirnameLocalSettings = path.join(
__dirname,
'/.data/local-settings.json'
"/.data/local-settings.json"
);
FS.writeFileSync(
dirnameLocalSettings,
@ -342,7 +342,7 @@ app.prepare().then(async () => {
});
});
server.post('/_/settings', async (req, res) => {
server.post("/_/settings", async (req, res) => {
let data;
try {
data = await PowerGate.ffs.setDefaultConfig(req.body.config);
@ -354,11 +354,11 @@ app.prepare().then(async () => {
return res.status(200).send({ success: true, data });
});
server.post('/_/local-settings', async (req, res) => {
server.post("/_/local-settings", async (req, res) => {
state.local = { ...state.local, ...req.body.local };
const dirnameLocalSettings = path.join(
__dirname,
'/.data/local-settings.json'
"/.data/local-settings.json"
);
FS.writeFileSync(
dirnameLocalSettings,
@ -368,7 +368,7 @@ app.prepare().then(async () => {
return res.status(200).send({ success: true });
});
server.post('/_/wallet/create', async (req, res) => {
server.post("/_/wallet/create", async (req, res) => {
let data;
try {
data = await PowerGate.ffs.newAddr(
@ -384,7 +384,7 @@ app.prepare().then(async () => {
return res.status(200).send({ success: true, data });
});
server.post('/_/wallet/send', async (req, res) => {
server.post("/_/wallet/send", async (req, res) => {
let data;
try {
data = await PowerGate.ffs.sendFil(
@ -402,18 +402,18 @@ app.prepare().then(async () => {
.send({ success: true, data: { ...data, ...req.body } });
});
server.get('/', async (req, res) => {
server.get("/", async (req, res) => {
if (!state.token) {
return res.redirect('/system');
return res.redirect("/system");
}
return app.render(req, res, '/', {
return app.render(req, res, "/", {
production,
wsPort,
});
});
server.get('*', async (req, res) => {
server.get("*", async (req, res) => {
return nextRequestHandler(req, res, req.url);
});