text
stringlengths
7
3.69M
var mongoose = require('mongoose'); var dbURI = 'mongodb://localhost:27017/SoundCloud'; mongoose.connect(dbURI); // 기본 설정에 따라 포트가 상이 할 수 있습니다. var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback () { console.log("mongo db connection OK."); }); var express = require('express') , http = require('http') , app = express() , server = http.createServer(app); var bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: false })); var urlencodedParser = bodyParser.urlencoded({ extended: false }); app.use(bodyParser()); app.use(bodyParser.text()); app.post('/', function (request, respond) { console.log(request.body); }); var Schema = mongoose.Schema; var userSchema = new Schema({ id : { type: String, required: true, unique: true }, name : { type: String}, state : {type: String}, //Lister or Musician accountnumber : {type : String}, bank : {type : String}, cash : {type : Number, default : 0}, follower : [String], following : [String], pop : {type : Boolean, default : false}, OST : {type : Boolean, default : false}, rap : {type : Boolean, default : false}, indi : {type : Boolean, default : false}, metal : {type : Boolean, default : false}, music : [String]//musician이라면 필요 }); var musicSchema = new Schema({ title : { type: String}, lyricist : {type: String}, //작사가 composer : {type : String},//작곡가 uploader : {type : String}, //upload한사람 singer : {type : String}, //가수 like_num : {type : Number, default : 0}, view_num : {type : Number, default : 0}, pop : {type : Boolean, default : false}, OST : {type : Boolean, default : false}, rap : {type : Boolean, default : false}, indi : {type : Boolean, default : false}, metal : {type : Boolean, default : false}, date : {type:Date, default:Date.now}, URL : {type : String} }); var User = mongoose.model('UserInfo', userSchema); var Music = mongoose.model('MusicInfo',musicSchema); app.post('/login', function (request, respond) { console.log("Got a POST/login request for the homepage\n"+JSON.parse(request.body).id); var newUsr = new User(); User.findOne({'id':JSON.parse(request.body).id},function(err,result){ if(err){ console.err(err); throw err; } if (result){ console.log("Find"); respond.write("Find"); } else { console.log("Not Find"); } }); }); app.post('/follow', function (req, res) { console.log("Got a POST/follow request for the homepage\n"+JSON.parse(req.body).followed); var newUsr = new User(); User.find({'id':JSON.parse(req.body).followed},function(err,result){ if(err){ console.err(err); throw err; } if(!result) return res.status(404).json({ error: 'id' }); result[0].follower.push(JSON.parse(req.body).following); result[0].save(function(err){ if(err) res.status(500).end("Failed"); //res.end("Success"); }); }); User.find({'id':JSON.parse(req.body).following},function(err,result){ if(err){ console.err(err); throw err; } if(!result) return res.status(404).json({ error: 'id' }); result[0].following.push(JSON.parse(req.body).followed); result[0].save(function(err){ if(err) res.status(500).end("Failed"); res.end("Success"); }); }); }); app.post('/register', function (request, respond) { console.log("Got a POST/register request for the homepage\n"+request.body); var newUsr = new User(JSON.parse(request.body)); newUsr.save(function(err){ if (err) { console.log("ERROR : POST/register request"); return; } }); }); app.post('/upload', function(request,respond) { console.log("Got a POST/upload request for the homepage\n"+request.body); var newMusic = new Music(JSON.parse(request.body)); newMusic.save(function(err){ if (err) { console.log("ERROR : POST/register request"); return; } }); var oldUser = new User(JSON.parse(newMusic.uploader)); User.find({"id":oldUser.id}, function(err, userinfo){ if(err) { return respond.status(500).json({ error: 'database failure' }); } if(!userinfo) { return respond.status(404).json({ error: 'id' }); } userinfo[0].music.push(newMusic.title); userinfo[0].save(function(err){ if(err) respond.status(500).end("Failed"); respond.end("Success"); }); }); }); app.post('/all/music', function(request,respond) { console.log("Got a POST/all/music request for the homepage\n"+request.body); var arr = []; Music.find({}, function(err, resultCursor) { if(err){ console.err(err); throw err; } for (var ob in resultCursor) { arr.push(resultCursor[ob]); } //console.log(arr); respond.send(arr); respond.end(); }); }); app.post('/search/music', function(request,respond) { console.log("Got a POST/search/music request for the homepage\n"+request.body); //var searchMusic = new Music(JSON.parse(request)); var searchMusic = JSON.parse(request.body); var arr = []; Music.find({}, function(err, resultCursor) { if(err){ console.err(err); throw err; } for (var ob in resultCursor) { for (var i in searchMusic) { if (i=="pop"){ if (resultCursor[ob].pop==true){ arr.push(resultCursor[ob]); break; } } if (i=="OST"){ if (resultCursor[ob].OST==true){ arr.push(resultCursor[ob]); break; } } if (i=="indi"){ if (resultCursor[ob].indi==true){ arr.push(resultCursor[ob]); break; } } if (i=="rap"){ if (resultCursor[ob].rap==true){ arr.push(resultCursor[ob]); break; } } if (i=="metal"){ if (resultCursor[ob].metal==true){ arr.push(resultCursor[ob]); break; } } } } //console.log(arr); respond.send(arr); respond.end(); }); }); app.get('/userinfo', function(req, res){ console.log("GET USERINFO"); //console.log(req.query.userinfo); var userinfo = JSON.parse(req.query.userinfo); var id = userinfo.id; console.log(id); res.end(id); }) app.get('/userinfo/:id', function(req, res){ User.findOne({"id":req.params.id}, function(err, userinfo){ if(err) return res.status(500).send({error: 'database failure'}); res.json(userinfo); console.log("Loading Complete"); }) }); app.put('/buycash/:id', function(req, res){ console.log("Buy Cash"); console.log(req.params.id); console.log(req.body); User.find({"id":req.params.id}, function(err, userinfo){ console.log(req.params.id); console.log(userinfo[0].cash); console.log(userinfo); if(err) return res.status(500).json({ error: 'database failure' }); if(!userinfo) return res.status(404).json({ error: 'id' }); userinfo[0].cash += parseInt(req.body.value); console.log(userinfo[0].cash); userinfo[0].save(function(err){ if(err) res.status(500).end("Failed"); res.end("Success"); }); }); }); app.post('/donatecash', function(req, res){ console.log("Donate Cash"); User.find({"id":JSON.parse(req.body).id}, function(err, userinfo){ if(err) return res.status(500).json({ error: 'database failure' }); if(!userinfo) return res.status(404).json({ error: 'id' }); console.log(userinfo[0].cash); console.log(JSON.parse(req.body).value); userinfo[0].cash -= parseInt(JSON.parse(req.body).value); console.log(userinfo[0].cash); userinfo[0].save(function(err){ if(err) res.status(500).end("Failed"); res.end("Success"); }); }); }); app.get('/getmusic/:title', function(req,res){ console.log("Get Music"); console.log(req.params.title); Music.find({"title":req.params.title}, function(err, musicinfo){ if(err) return res.status(500).json({error:'database failure'}); if(!musicinfo) return res.status(404).json({error:'music'}); var url = musicinfo[0].URL; console.log(url); res.write(url) res.send(); }) }); app.post('/likemusic', function(req,res){ console.log("Get Music"); console.log(req.body); Music.find({"URL":JSON.parse(req.body).URL}, function(err, musicinfo){ if(err) { return res.status(500).json({error:'database failure'}); } if(!musicinfo) { return res.status(404).json({error:'music'}); } console.log(musicinfo[0].like_num); musicinfo[0].like_num++; console.log(musicinfo[0].like_num); musicinfo[0].save(function(err){ if(err) res.status(500).end("Failed"); res.end("Success"); }); }) }); app.post('/detailmusic', function(req,res){ console.log("Detail Music"); console.log(req.body); Music.find({"URL":JSON.parse(req.body).URL}, function(err, musicinfo){ if(err) { return res.status(500).json({error:'database failure'}); } if(!musicinfo) { return res.status(404).json({error:'music'}); } console.log(musicinfo[0]); //res.write(musicinfo[0]); res.send(musicinfo[0]); res.end(); }) }); app.get('/userinfo/follower/:id', function(req,res){ console.log("Get follower"); console.log(req.params.id); User.find({"id":req.params.id}, function(err, userinfo){ console.log(userinfo); if(err) return res.status(500).json({error:'database failure'}); if(!userinfo) return res.status(404).json({error:'id'}); console.log(userinfo[0].follower); res.write(userinfo[0].follower.toString()); res.send(); }) }); app.get('/userinfo/following/:id', function(req,res){ console.log("Get following"); console.log(req.params.id); User.find({"id":req.params.id}, function(err, userinfo){ console.log(userinfo); if(err) return res.status(500).json({error:'database failure'}); if(!userinfo) return res.status(404).json({error:'id'}); console.log(userinfo[0].following); res.write(userinfo[0].following.toString()); res.send(); }) }); app.get('/userinfo/musics/:id', function(req,res){ console.log("Get Musics"); console.log(req.params.id); User.find({"id":req.params.id}, function(err, userinfo){ console.log(userinfo); if(err) return res.status(500).json({error:'database failure'}); if(!userinfo) return res.status(404).json({error:'id'}); console.log(userinfo[0].music); res.write(userinfo[0].music.toString()); res.send(); }) }); server.listen(1337, function() { //console.log('Express server listening on port ' + server.address().port); });
console.log("Up and running!"); var cards = ["queen", "queen", "king", "king"]; var cardsInPlay = ["cardOne"]; var cardOne = ["queen"]; cardOne = ["0"]; cardsInPlay .push("cardOne"); console.log("User flipped queen"); var cardTwo = ["queen"]; cardOne = ["1"]; cardsInPlay.push("cardTwo"); console.log("User flipped queen"); var cardThree = ["king"]; cardOne = ["2"]; cardsInPlay.push("cardThree"); console.log("User flipped king"); var cardFour = ["king"]; cardOne = ["3"]; cardsInPlay.push("cardFour"); console.log("User flipped king"); alert('Hello, friends.');
// const upload = require('../library/uploadMiddleware'); const Resize = require('../library/Resize'); const Config = require('../globals/Config'); const path = require('path'); const mkdirp = require('mkdirp') const uuidv4 = require('uuid/v4'); var multer = require('multer') var fs = require('fs'); var dir = './public_images'; if (!fs.existsSync(dir)) { fs.mkdirSync(dir); } const _config = new Config(); module.exports = function (app) { //############################################################################################################# //############################################################################################################# //################################################ Upload Route ############################################### //############################################################################################################# //############################################################################################################# app.post('/delete-image', function (req, res) { const subPath = '../public_images/' + req.body.folder_name + "/" + req.body.image_name const dir = path.join(__dirname, subPath) if (fs.existsSync(dir)) { fs.unlink(dir, (err) => { if (err) { console.error(err) require = { data: { req: false }, error: { message: 'Delete photo not complete.' }, upload_result: true, server_result: true }; res.send(require) } else { require = { data: { req: true }, error: { message: 'Delete photo complete.' }, upload_result: true, server_result: true }; res.send(require) } }) } else { require = { data: { req: false }, error: { message: 'This directory does not exist' + dir }, upload_result: true, server_result: true }; res.send(require) } }); app.post('/upload-file', function (req, res) { console.log(req); const multer = require('multer'); var filePathSub = ''; var Storage = multer.diskStorage({ destination: function (req, file, callback) { console.log(">>>>>>", req.params); const userPath = _config.getInt2Text(req.body.menuscript_code) + "/" + req.body.upload_url; const subPath = '../../public_file/menuscript/' + userPath; const filePath = path.join(__dirname, subPath); filePathSub = 'public_file/menuscript/' + userPath; // if (!fs.existsSync(imagePath)) { // fs.mkdirSync(imagePath); // } mkdirp.sync(filePath) callback(null, filePath); }, filename: function (req, file, callback) { console.log("file : ", req.body); callback(null, uuidv4() + req.body.file_type); } }); var upload = multer({ storage: Storage }).single("files"); upload(req, res, function (err) { // console.log('req',req) if (!req.file) { const require = { data: { comment_photo_url: '' }, error: [{ message: 'Can not find photo upload.' }], upload_result: false, server_result: true }; res.send(require); } else { const comment_photo_url = _config.getServerUrl() + "/" + filePathSub + "/" + req.file.filename const require = { data: [{ comment_photo_url: comment_photo_url }], error: [{ message: 'Upload photo complete.' }], upload_result: true, server_result: true }; console.log('res', require); res.send(require); } }); }); app.post('/upload-image', async function (req, res) { // const userPath = req.body.upload_url + "/" // const subPath = '../public_images/' + userPath; // const imagePath = path.join(__dirname, subPath); var filePathSub = ''; var Storage = multer.diskStorage({ destination: function (req, file, callback) { console.log("body = >", req.body); console.log(">>>>>>", req.params); console.log(">>>>>>", file); const userPath = req.body.upload_url + "/" const subPath = '../public_images/' + userPath; filePathSub = path.join(__dirname, subPath); //filePathSub = 'public_file/' + req.body.upload_url + '/' + userPath; mkdirp.sync(filePathSub) callback(null, filePathSub); }, filename: function (req, file, callback) { // console.log("file : ",req.file.filename); callback(null, uuidv4() + req.body.file_type); } }); var upload = multer({ storage: Storage }).single("files"); upload(req, res, function (err) { console.log("body = >", req.body); console.log(">>>>>>", req.body.upload_url); console.log('req',req.file) if (!req.file) { const require = { data: { comment_photo_url: '', photo_url: "" }, error: [{ message: 'Can not find photo upload.' }], upload_result: false, server_result: true }; res.send(require); } else { const comment_photo_url = req.body.upload_url + "/" + req.file.filename const require = { data: { comment_photo_url: comment_photo_url, photo_url: req.file.filename }, error: [{ message: 'Upload photo complete.' }], upload_result: true, server_result: true }; console.log('res', require); res.send(require); } }); }); }
define([ 'jquery', 'underscore', 'backbone', 'backbones/views/components/showArea', 'backbones/views/components/previewArea', 'backbones/views/components/chatArea' ], function($, _, Backbone, ShowArea, PreviewArea, ChatArea){ var RoomSubviews = function(rootEl, app){ this.rootEl = rootEl; this.app = app; this.subviewConfig = { "#show-area":ShowArea, "#preview-area":PreviewArea, "#chat-area":ChatArea }; this.subviews = null; this.render = function(){ this.subviews = {}; console.log("Room view rerender! "+this.app.status); for (var subviewId in this.subviewConfig){ var initFunc = this.subviewConfig[subviewId]; this._renderSubview(subviewId,initFunc); }; return this; }; this._renderSubview = function(htmlId,initFunc){ console.log("Render "+htmlId); this.subviews[htmlId] = new initFunc(this.app); this.rootEl.find(htmlId).append(this.subviews[htmlId].render().el); }; this.isInitialized = function(){ console.log(this.subviews); if (this.subviews !== null){ console.log("[Subviews]: initialized"); return true; } else{ console.log("[Subviews]: not initialized"); return false; } }; this.onShow = function(){ for (var subviewId in this.subviews){ var subview = this.subviews[subviewId]; if (subview.onShow){ subview.onShow(); } } }; }; return RoomSubviews; });
// import functions and grab DOM elements // initialize state // set event listeners to update state and DOM import { countsAsAYes } from './src/counts-as-a-yes/utils.js'; const button = document.getElementById('quizButton'); const result = document.getElementById('displayScore'); button.addEventListener('click', () => { alert('Welcome to the Quiz'); const confirmQuiz = confirm('Do you REALLY want to take the quiz?'); if (!confirmQuiz) { alert('A computer is like an air conditioner. It works fine until you open windows.'); return; } const name = prompt('What\'s your name?'); const firstAnswer = prompt('Arch aims to be user friendly.'); const secondAnswer = prompt('Arch is an operating system that\'s updated every minute.'); const thirdAnswer = prompt('LOTS of people make software for Arch that\'s available in the Arch User respository.'); let score = 1; if (countsAsAYes(secondAnswer)) { score++; } if (countsAsAYes(thirdAnswer)) { score++; } if (countsAsAYes(firstAnswer)) { score--; } const finalScore = score / 3 * 100; if (score === 3) { result.style.backgroundColor = 'hsla(206, 46%, 37%, 1)'; result.textContent = `${name}....you scored ${+finalScore.toFixed(0)}%. You're a wizard`; } else if (score === 2) { result.style.backgroundColor = 'hsla(21, 89%, 52%, 1)'; result.textContent = `${name}....you scored ${+finalScore.toFixed(0)}%. So close.`; } else { result.style.backgroundColor = 'red'; result.textContent = `${name}....you scored ${+finalScore.toFixed(0)}%. READ AGAIN.`; } });
const mongoose = require('mongoose'); const db = require('./config.js') const profileSchema = mongoose.Schema({ image: String, name: String, city: String, rating: Number, reviewCount: Number }) const Profile = mongoose.model('Profile', profileSchema); module.exports = Profile;
import React, {PropTypes}from 'react'; import withStyle from 'isomorphic-style-loader/lib/withStyles'; import s from './receiveChange.less'; import {Indent, Title, SuperForm, SuperTable2, SuperToolbar, SuperTable} from '../../../components'; class EditPage extends React.Component{ static propTypes = { controls: PropTypes.array, value: PropTypes.object, tables: PropTypes.array }; toForm() { const {controls=[], value={}, valid, onChange, onFormSearch, onExitValid} = this.props; return ( <div> {controls.map((item, index) => { const changeEvent = onChange.bind(null, item.key); const searchEvent = onFormSearch.bind(null, item.key); const exitValidEvent = onExitValid.bind(null, item.key); const props = { value: {...value}, valid: valid === item.key, controls: item.data, onChange: changeEvent, onSearch: searchEvent, onExitValid: exitValidEvent }; return ( <div key={index}> <Title title = {item.title}/> <Indent className={s.form}> <SuperForm {...props}/> </Indent> </div> ) })} </div> ) } toSuperTable (){ const {tables, value={}} = this.props; return( <div> { tables.map(item => { const newCols = item.cols.filter(col => (col.type !== 'checkbox')&&(col.type !== 'index')); const superTableProps = { cols: newCols, items: value[item.key], checkbox: false }; return ( <div key={item.key}> <Title title={item.title} /> <Indent className={s.tableInfo}> <SuperTable {...superTableProps} /> </Indent> </div> ); }) } </div> ) } toSuperTable2() { const {tables, value={}, valid, onClick, onContentChange, onExitValid, onSearch, isReadOnly} = this.props; return( <div> { tables.map((item, index) => { const clickEvent = onClick.bind(null, item.key); const contentChange = onContentChange.bind(null, item.key); const searchEvent = onSearch.bind(null, item.key); const btnProps = {buttons: item.btns, size: 'small', onClick: clickEvent}; const tableProps = { cols: item.cols, items: value[item.key] || [], valid: valid === item.key, callback: {onCheck: contentChange, onSearch: searchEvent, onContentChange: contentChange, onExitValid} }; return ( <div key={index}> <Title title={item.title} /> <Indent className={s.tableInfo}> {!isReadOnly && <SuperToolbar {...btnProps} />} <SuperTable2 {...tableProps}/> </Indent> </div> ) })} </div> ) } toFooter() { const {footerButtons, onClick, AuditFooter, isAudit} = this.props; const footerProps = { buttons: isAudit ? AuditFooter :footerButtons, size: 'default', onClick: onClick.bind(null, undefined) }; return ( <div className={s.footer}> <SuperToolbar {...footerProps}/> </div> ) } render(){ const {isReadOnly, isAudit} = this.props; return ( <div className={s.root}> {this.toForm()} {isReadOnly ? this.toSuperTable() : this.toSuperTable2()} {(!isReadOnly || isAudit) && this.toFooter()} </div> ) } } export default withStyle(s)(EditPage);
var functions__a_8js = [ [ "c", "functions__a_8js.html#a08907b9bca25be2ebc6b009e19f9d23b", null ], [ "searchData", "functions__a_8js.html#ad01a7523f103d6242ef9b0451861231e", null ] ];
const cp = require( "child_process" ); const path = require( "path" ); const DIR = path.join( __dirname, "nyc" ); QUnit.module( "nyc", { before: () => { cp.execSync( "npm install --prefer-offline --no-audit", { cwd: DIR, encoding: "utf8" } ); } } ); QUnit.test( "test", assert => { const expected = ` TAP version 13 ok 1 add > two numbers 1..1 # pass 1 # skip 0 # todo 0 # fail 0 --------------|---------|----------|---------|---------|------------------- File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s --------------|---------|----------|---------|---------|------------------- All files | 85.71 | 100 | 50 | 85.71 | nyc | 100 | 100 | 100 | 100 | index.js | 100 | 100 | 100 | 100 | nyc/src | 75 | 100 | 50 | 75 | add.js | 100 | 100 | 100 | 100 | subtract.js | 50 | 100 | 0 | 50 | 2 --------------|---------|----------|---------|---------|------------------- `.trim(); const actual = cp.execSync( "npm test", { cwd: DIR, encoding: "utf8" } ); assert.pushResult( { result: actual.includes( expected ), actual, expected } ); } );
const ZtMeta = require("../lib"); it("listTables without columns and primary key",()=>{ let ztmeta=new ZtMeta({ host:'127.0.0.1', user:'root', password:'123456' }); // notice use yourself database data ztmeta.listTables("security_oauth",{},(err,data,info)=>{ expect(data[0].table_name).toBe('t_permission'); }) }); it("listTables without columns but with primary key",()=>{ let ztmeta=new ZtMeta({ host:'127.0.0.1', user:'root', password:'123456' }); // notice use yourself database data ztmeta.listTables("security_oauth",{},(err,data,info)=>{ expect(data[0].primary_key.col_name).toBe("aa"); }) });
const { loadEnv } = require('./config') const env = loadEnv({ RELEASE_DATE: new Date(), RELEASE_VERSION: process.env.RELEASE_VERSION || new Date().getTime(), }) module.exports = { siteMetadata: { title: `Super Integrity`, description: `Super Integrity`, author: `engineforce@gmail.com`, mapApiKey: process.env.MAP_API_KEY, }, plugins: [ `gatsby-plugin-react-helmet`, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, { resolve: `gatsby-source-filesystem`, options: { name: 'about-images', path: `${__dirname}/src/components/about-page/images`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-manifest`, options: { name: `super-integrity`, short_name: `super`, start_url: `/`, background_color: `#a69576`, theme_color: `#a69576`, display: `minimal-ui`, icon: `src/images/super-integrity.png`, // This path is relative to the root of the site. }, }, `gatsby-plugin-styled-components`, { resolve: 'gatsby-plugin-web-font-loader', options: { google: { families: ['Libre Baskerville'], }, }, }, { resolve: `gatsby-plugin-env-variables`, options: { whitelist: Object.keys(env), }, }, { resolve: 'gatsby-plugin-google-tagmanager', options: { id: 'GTM-T8FBMTB', // Include GTM in development. // Defaults to false meaning GTM will only be loaded in production. includeInDevelopment: false, // datalayer to be set before GTM is loaded // should be an object or a function that is executed in the browser // Defaults to null defaultDataLayer: { platform: 'gatsby' }, }, }, ], }
import { Message } from './dist/src/message'; import { SubscribedConnection } from './dist/src/subscribedConnection'; import { Quetify } from './dist/src/quetify';
document.addEventListener('DOMContentLoaded',()=>{ fetch('process/agency-search-process.php') .then((response)=>{ console.log(response); return response.json(); }).then((results)=>{ search(results) }) }) function search(results){ let search = document.querySelector("#search-agency"); let divAgency = document.querySelector(".agency-list"); search.addEventListener("input", (event)=>{ searchAgency = event.target.value divAgency.innerHTML = '' results.forEach(result => { if (result.name.includes(searchAgency) ) { console.log(result); divAgency.innerHTML += ` <div class="card-info-destination col-xl-3 col-md-5 col-sm-12 p-2 m-3"> <img class="card-img-top" src="${result.photo_link}"> <div class="card-info"> <h5>${result.name}</h5> <div class="card-sub-info"> <p><?=$operator->getGrade()== null ? "Note global : Pas de note pour l'instant" : "Note global : " . ${result.grade} . " / 5 <br>";?></p> </div> </div> </div>` } }); }); }
import { useState, useEffect } from 'react'; import { useSelector, useDispatch } from 'react-redux'; import routes from '../../routes'; import Button from '../../components/Button/Button'; import { getProducts } from '../../redux/selectors'; import cardActions from '../../redux/card/card-action'; import { Container, ProductColor, SelectContainer, } from './ProductDetailsPage.style'; const ProductDetailsPage = ({ match, history }) => { const { params: { productId }, } = match; const dispatch = useDispatch(); const products = useSelector(getProducts); const [product, setProduct] = useState(() => products.find(prod => prod.id === productId), ); const [prise, setPrise] = useState(product?.price); const [something, setSomething] = useState(0); const [amount, setAmount] = useState(1); useEffect(() => { if (!product) { history.push(routes.home); } }, []); const addSomething = ({ target }) => { setSomething(Number(target.value)); setPrise((product.price + Number(target.value)) * amount); }; const isClearPrice = () => { setPrise(product.price); setAmount(1); setSomething(0); }; const isSubtract = () => { if (amount === 1) return; setPrise(prise - prise / amount); setAmount(amount - 1); }; const isAddAmount = () => { setPrise(prise + prise / amount); setAmount(amount + 1); }; const isAddToCard = () => { const productId = something ? `${product.id}/${something}` : product.id; dispatch( cardActions.addToCard({ ...product, id: productId, amount: amount, price: prise / amount, }), ); }; return ( <> <h2>ProductDetailsPage</h2> <Container> <ProductColor color={product?.color}> Color: {product?.color} <p>Price: {product?.price}$</p> </ProductColor> <div> <p>Price: {prise}$</p> <SelectContainer> <select name="something" value={something} onChange={addSomething}> <option value="0">0$</option> <option value="10">Small 10$</option> <option value="20">Medium 20$</option> <option value="30">Large 30$</option> </select> <button onClick={isClearPrice}>Clear</button> </SelectContainer> <div> <button onClick={isSubtract} disabled={amount < 2 ? true : false}> -1 </button> <span>{amount}</span> <button onClick={isAddAmount}>+1</button> </div> </div> </Container> <Button text="Add to Card" onClick={isAddToCard}></Button> </> ); }; export default ProductDetailsPage;
const fs = require("fs"), https = require("https"), crypto = require("crypto"), readline = require("readline"); const store = "store.json"; const allowManyRequests = true; const options = { key: fs.readFileSync("key.pem"), cert: fs.readFileSync("cert.pem") }; const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); rl.question("Encryption passphrase: ", (r) => { const ehash = crypto.createHash("sha256"); ehash.update(Buffer.from(r)); const enc = ehash.digest(); if (!enc) return; const server = https.createServer(options, (req, res) => { if (req.method == "POST") { const h = req.headers; console.log("---\nIncoming: ", req.url, "\n", h); const socket = req.socket; //socket.remoteAddress: IP let data, st = {}; //data: buffer if (fs.existsSync(store)) { const f = fs.readFileSync("store.json"); st = JSON.parse(f); if (!st) res.end(500); } else { console.log("Creating store.json."); fs.writeFileSync("store.json", JSON.stringify({})); } const ip = socket.remoteAddress; let Status = 400, Headers = {}, Body = ""; //return data if (!st.iplog) { st.iplog = {}; st.iplog[ip] = Date.now(); fs.writeFileSync(store, JSON.stringify(st)); } const tl = Date.now() - st.iplog[ip]; //time since last request if (tl < 15000 && allowManyRequests == false) { Status = 429; //Too Many Requests } else { st.iplog[ip] = Date.now(); fs.writeFileSync(store, JSON.stringify(st)); } req.on("data", (chunk) => { data = Buffer.from(chunk); }); req.on("end", () => { if (!data) Status = 406; else { console.log("buf[" + data.length + "] " + data.toString("hex")); } if (Status == 429) { //prevent DDoS console.log("delaying request from", ip); } else { if (req.url == "/key") { if (data.length != 32) { //AES key length Status = 406; //Not Acceptable } else { const hash = crypto.createHash("sha512"); hash.update(data); const id = hash.digest(); const aes = crypto.createCipheriv("aes256", enc, Buffer.alloc(16)); const key1 = aes.update(data); const key2 = aes.final(); const key = Buffer.concat([key1, key2]); const obj = { "id": id.toString("hex"), "key": key.toString("hex"), "unlocked": false, "ip": ip }; if (!st[id]) { console.log("-> Storing:\n", obj); st[id] = obj; fs.writeFileSync(store, JSON.stringify(st)); } Status = 201; //Created Headers["Content-Type"] = "application/octet-stream"; Body = id; //give id } } else if (req.url == "/id") { if (data.length != 512 / 8) { //SHA512 hash length Status = 406; } else { const id = data; if (st[id]) { let key = Buffer.from(st[id]["key"], "hex"); //build buffer from hex string //check if hash(dec(key))=id const aes = crypto.createDecipheriv("aes256", enc, Buffer.alloc(16)); const key1 = aes.update(key); const key2 = aes.final(); key = Buffer.concat([key1, key2]); const hash = crypto.createHash("sha512"); hash.update(key); const rev = hash.digest(); console.log(id, rev, Buffer.compare(id, rev)); if (Buffer.compare(id, rev) != 0) { Status = 401; //Unauthorized console.log("key hash =/= given id"); } else { console.log("-> unlocked: ", st[id]["unlocked"]); if (st[id]["unlocked"] == true) { Status = 200; Headers["Content-Type"] = "application/octet-stream"; Body = key; } else { Status = 402; //Payment Required } } } else { Status = 404; //Not Found } } } } res.writeHead(Status, Headers); res.end(Body); console.log("Outgoing: ", Status, "\n", Body, "\n---\n"); }); } else { res.writeHead(405, "Method not allowed"); res.end(); } }).listen(5500); }); //end of rl.question
export const dimBackground = () => { const bgDim = document.querySelector('.bg-focus'); bgDim.style.display = 'block'; }; export const lightBackground = () => { const bgLight = document.querySelector('.bg-focus'); bgLight.style.display = 'none'; };
'use babel'; const CONFIG_DEFAULT_HOST = 'https://phabricator.example.com/api/'; const CONFIG_DEFAULT_TOKEN = 'api-XYZ'; const CONNECTING_MESSAGE = 'Checking connection to Diffusion...'; function rangeToString(range) { if (range.start.row === range.end.row) { return range.start.row + 1; } else { return (range.start.row + 1) + '-' + (range.end.row + 1); } } function simplifyProjectName(name) { return (name || '').trim().toLowerCase().replace(/[\s\-_()]/g, ''); } function requireApiUrl(url) { // remove first so we don't double-add it if it's already there return removeApiFromUrl(url) + '/api/'; } function removeApiFromUrl(url) { return url.replace(/\/api?\/$/, ''); } let _phabHost = null; function getDiffusionHost() { const host = atom.config.get('open-in-diffusion.conduit-host'); if (host !== CONFIG_DEFAULT_HOST) { return Promise.resolve(removeApiFromUrl(host)); } if (_phabHost) { return _phabHost; } return new Promise((resolve, reject) => { const arcrc = require('path').join(process.env.HOME, '.arcrc'); require('fs').readFile(arcrc, function (err, data) { if (err) { reject(err); }; try { const config = JSON.parse(data); _phabHost = removeApiFromUrl(Object.keys(config.hosts)[0]); resolve(_phabHost); } catch (e) { reject(e); } }); }); } export default { subscriptions: null, canduit: null, foundProjects: {}, config: { 'conduit-host': { title: 'Optional: Conduit API endpoint', description: 'URL to the phabricator instance API, usually ends with `/api/`', type: 'string', default: CONFIG_DEFAULT_HOST, }, 'conduit-token': { title: 'Optional: Conduit API Token', description: 'Get a Standard API Token from https://phabricator.example.com/settings and clicking on "Conduit API Tokens".', type: 'string', default: CONFIG_DEFAULT_TOKEN, }, }, activate() { this.subscriptions = new (require('atom').CompositeDisposable)(); this.subscriptions.add( atom.config.onDidChange('open-in-diffusion.conduit-host', () => { this.connectToConduit(); }) ); this.subscriptions.add( atom.config.onDidChange('open-in-diffusion.conduit-token', () => { this.connectToConduit(); }) ); this.subscriptions.add(atom.commands.add('atom-workspace', { 'open-in-diffusion:clear-project-cache': () => { this.foundProjects = {}; }, 'open-in-diffusion:open-in-phabricator': () => { const editor = atom.workspace.getActiveTextEditor(); if (!editor) { return; } this.openInDiffusion( editor.getPath(), editor.getSelectedBufferRanges() ); }, 'open-in-diffusion:copy-phabricator-url': () => { const editor = atom.workspace.getActiveTextEditor(); if (!editor) { return; } this.getDiffusionUrl( editor.getPath(), editor.getSelectedBufferRanges() ).then((url) => { atom.clipboard.write(url); }); } })); this.connectToConduit(); }, consumeSignal(registry) { this.provider = registry.create(); this.subscriptions.add(this.provider) }, deactivate() { this.subscriptions.dispose(); }, serialize() { return {}; }, conduitConfig() { const host = requireApiUrl(atom.config.get('open-in-diffusion.conduit-host')); const token = atom.config.get('open-in-diffusion.conduit-token'); if (host === CONFIG_DEFAULT_HOST || token === CONFIG_DEFAULT_TOKEN) { return {}; } else { return {api: host, token: token}; } }, conduitFactory() { return new Promise((resolve, reject) => { const Canduit = require('canduit'); new Canduit(this.conduitConfig(), (err, canduit) => { if (err) { reject(err); } resolve(canduit); }); }); }, connectToConduit() { this.provider && this.provider.add(CONNECTING_MESSAGE); this.canduit = null; this.conduitFactory() .then((canduit) => { this.canduit = canduit; console.info(`[open-in-diffusion] Successfully connected to diffusion.`); this.provider && this.provider.remove(CONNECTING_MESSAGE); }); }, genRepositorySearch(search) { return this.genExecPhabricatorQuery('diffusion.repository.search', { queryKey: ['active'], constraints: { query: search, }, }); }, genExecPhabricatorQuery(endpoint, options) { return new Promise((resolve, reject) => { if (!this.canduit) { reject('Not yet connected to canduit'); } this.canduit.exec(endpoint, options, (err, response) => { if (err) { reject(err); return; } resolve(response); }); }); }, genFindPhabProject(projectPath) { const searchTerm = require('path').basename(projectPath); if (this.foundProjects[projectPath]) { return Promise.resolve(this.foundProjects[projectPath]); } else { return this.genRepositorySearch(searchTerm) .then((response) => { this.foundProjects[projectPath] = this.getMatchingPhabProject(response.data, searchTerm); return this.foundProjects[projectPath]; }); } }, getMatchingPhabProject(data, searchTerm) { const simpleSearchTerm = simplifyProjectName(searchTerm); const names = data.map((data) => { if (!data.fields) { return null; } return { name: simplifyProjectName(data.fields.name), shortName: simplifyProjectName(data.fields.shortName), callsign: simplifyProjectName(data.fields.callsign), project: data, }; }).filter(Boolean); const nameMatches = names.filter((item) => item.name === simpleSearchTerm); if (nameMatches.length) { return nameMatches.shift().project; } const shortNameMatches = names.filter((item) => item.shortName === simpleSearchTerm); if (shortNameMatches.length) { return shortNameMatches.shift().project; } const callSignMatches = names.filter((item) => item.callsign === simpleSearchTerm); if (callSignMatches.length) { return callSignMatches.shift().project; } throw Error(`No project found matching ${searchTerm}`); }, getProjectPath(filePath) { return atom.project.getPaths() .filter((path) => filePath.startsWith(path)) .shift(); }, getDiffusionUrl(nuclideFilePath, selectedRanges) { this.provider && this.provider.add(CONNECTING_MESSAGE); const projectPath = this.getProjectPath(nuclideFilePath); const relativeFilePath = nuclideFilePath.replace(projectPath, ''); const range = '$' + selectedRanges .map(rangeToString) .join(','); return Promise.all([ getDiffusionHost(), this.genFindPhabProject(projectPath) ]).then(([host, project]) => { console.log({host, project}); const id = project.fields.callsign ? project.fields.callsign : project.id; console.log('id', id); const url = `${host}/diffusion/${id}/browse/master${relativeFilePath}${range}`;; console.log('url', url); return url; }); }, openInDiffusion(nuclideFilePath, selectedRanges) { this.getDiffusionUrl(nuclideFilePath, selectedRanges) .then((url) => { console.log('got a url', url); require('opn')(url); this.provider && this.provider.remove(CONNECTING_MESSAGE); }) .catch((message) => { console.warn(`[open-in-diffusion] Unable to open ${nuclideFilePath}. ${message}`); this.provider && this.provider.remove(CONNECTING_MESSAGE); const errorMessage = `Unable to open ${nuclideFilePath}`; this.provider && this.provider.add(errorMessage); setTimeout(() => { this.provider && this.provider.remove(errorMessage); }, 2000); }); }, };
"use strict"; $(document).ready(function () { var newTextField = $(".new-line"); var list = $(".list"); var createButton = $(".create"); createButton.click(function () { var text = newTextField.val(); if (text === "") { return; } var li = $("<li>"); createBasicLi(text); var children = li.children(); function deleteLine() { li.remove(); } function edit() { var tempText = children.eq(0).text(); li.html("<input type='text' />\ <button type='button'>Decline</button>\ \<button type='button'>Save</button>"); children = li.children(); children.eq(0).val(tempText); children.eq(1).click(decline); children.eq(2).click(save); } function decline() { createBasicLi(text); } function save() { var tempText = children.eq(0).val(); text = children.eq(0).val(); createBasicLi(tempText); } function createBasicLi(text) { li.html("<span></span>\ <button type='button'>X</button>\ <button type='button'>Edit</button>"); children = li.children(); children.eq(0).text(text); children.eq(1).click(deleteLine); children.eq(2).click(edit); } list.append(li); newTextField.val(""); }); });
//Turns raspberry pi connected led on/off via socket.io const app = require('express')(); /* * still don't understand why we need express and http; http object may be needed to initialize socket.io object */ const server = require('http').Server(app); const io = require('socket.io')(server); const express = require('express'); const staticAssets = __dirname + "/public"; const raspi = require('raspi-io'); //can only be installed on raspiberry pi machine const five = require('johnny-five'); const board = new five.Board({ io: new raspi() }); app .use("/", express.static(staticAssets)) ; io.on('connection', function(socket) { console.log('Connected'); socket.on('disconnect', function() { console.log('Disconnected'); }) socket.on('client-wave', function(wave) { console.log(wave.greeting); io.emit('server-wave', { greeting: 'Hello from server' }); //led on board.on('ready', () => { // Create an Led on pin 7 on header P1 (GPIO4) and strobe it on/off const led = new five.Led('P1-7'); led.strobe(); }); }) socket.on('client-bye', function(wave) { console.log(wave.greeting); //led off board.on('ready', () => { const led = new five.Led('P1-7'); led.strobe() }); io.emit('server-wave', { greeting: 'Bye' }); }) }); server.listen(3000, function(){ console.log("Listening on port:3000"); });
/** * @typedef Message * @type {object} * @property {string} id * @property {string} subject * @property {string} body * @property {object} from * @property {string} from.name * @property {string} from.email * @property {object} to * @property {string} to.name * @property {string} to.email * @property {string} date */ /** * @type Message[] */ let messages = [ { id: "1", from: { name: "GitHub", email: "noreply@github.com", }, to: { name: "Logan McAnsh", email: "logan@remix.run", }, subject: "[GitHub] A personal access token has been added to your account", body: "Hey mcansh!\n\nA personal access token.....................", date: "2021-10-12T15:30:33.566Z", }, { id: "2", from: { name: "Remix", email: "news@github.com", }, to: { name: "Logan McAnsh", email: "logan@remix.run", }, subject: "Remix Goes Open Source, Raises Seed Funding", body: "Thanks for following our journey as we built Remix", date: "2021-10-11T19:26:00.000Z", }, { id: "3", from: { name: "GitHub", email: "noreply@github.com", }, to: { name: "Logan McAnsh", email: "logan@remix.run", }, subject: "[GitHub] Payment Receipt for mcansh", body: "We received payment for your GitHub.com subscription. Thanks for your business!", date: "2021-10-05T15:30:33.566Z", }, ]; /** * * @param {string} id * @returns {Message | undefined} */ function getMessageById(id) { return messages.find((message) => message.id === id); } export { messages, getMessageById };
const express = require('express'); const path = require('path'); const bodyParser= require('body-parser'); const mongoose = require('mongoose'); const postRoutes = require ("./routes/posts"); const app = express(); mongoose.connect("mongodb+srv://jrmartins89:Thepillows1@cluster0.v0krp.mongodb.net/myFirstDatabase?retryWrites=true&w=majority").then(()=>{ console.log("Connected to database!"); }).catch(()=>{ console.log("Connection failed!"); }); //this function will return a valid middleware for parsing json data app.use(bodyParser.json()); //the argument extended:false is to make sure only default features are supported in the url enconding app.use(bodyParser.urlencoded({extended:false})); //any requests targeting /images will be allowed to continue and fetch the images from the folder. the path function //at the end makes sure the requests that target /images will be forwarded to 'backend/images'. app.use("/images",express.static(path.join("backend/images"))); app.use((req,res,next)=>{ //this means that it doesn't matter which domain the app that is sending the request is running on. It is allowed //to access the resources of the other domain (server) res.setHeader("Access-Control-Allow-Origin","*"); //restrict to domains sending requests with a certain set of headers besides the default header. the other headers are // the other arguments. this means the incoming request can have these extra headers. It doesnt have to, but it can have it. res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); //Here we control which http words may be used to send requests res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS"); next(); }); //all the requests reaching localhost/3000/posts will reach this middleware app.use("/api/posts", postRoutes); module.exports=app;
import React from 'react'; import './styles.css' import Logo from './logo.png' const nav = () => { return( <nav class="navbar navbar-expand-lg bg-secondary text-uppercase fixed-top" id="mainNav"> <div class="container"> <img alt='logo' src={Logo}/> <a class="navbar-brand js-scroll-trigger">Footcentage</a> <div class="collapse navbar-collapse" > <ul class="navbar-nav ml-auto"> <li class="nav-item mx-0 mx-lg-1"><a class="nav-link py-3 px-0 px-lg-3 rounded js-scroll-trigger" href="#games">Fixtures</a></li> <li class="nav-item mx-0 mx-lg-1"><a class="nav-link py-3 px-0 px-lg-3 rounded js-scroll-trigger" href="#about">About</a></li> </ul> </div> </div> </nav> ); } export default nav;
import React, { Component } from 'react'; import MusicControls from './MusicControls.jsx'; import MusicProgress from './MusicProgress.jsx'; export default class TypePlayList extends Component { render() { return ( <div className={this.props.className}> <div className="jp-gui jp-interface flex-wrap d-flex justify-content-center"> <MusicControls className="jp-controls flex-item" onPlayPause={this.props.onPlayPause} onNext={this.props.onNext} onPrevious={this.props.onPrevious} paused={this.props.paused} /> <MusicProgress currentTime={this.props.currentTime} duration={this.props.duration} onTimeChange={this.props.onTimeChange} className="jp-progress-container flex-item"/> </div> </div> ); }; }
//Import a library to help create a component import React from 'react'; import { AppRegistry, View } from 'react-native'; import FraphoList from './src/components/FraphoList'; import { StackNavigator } from 'react-navigation'; import ControlCenter from './src/components/ControlCenter'; import ScanScreen from './src/components/ScanScreen'; const RootNavigator = StackNavigator({ FraphoList: { screen: FraphoList, }, ControlCenter: { screen: ControlCenter, }, ScanScreen: { screen: ScanScreen, } }); //Creat a component const App = () => ( <View style={styles.containerStyle}> <RootNavigator /> </View> ); const styles = { containerStyle: { flex: 1 } }; //render it to the screen AppRegistry.registerComponent('Frapho', () => App); export default App;
var searchData= [ ['normalize',['normalize',['../classsrc_1_1_utilities.html#a1349f52c9c87649616199d6d9555d855',1,'src::Utilities']]] ];
var searchData= [ ['mainbuttoncanvas_30',['mainButtonCanvas',['../class_scene_handler.html#a0776102bd31d56e4d67f43655b67c274',1,'SceneHandler']]], ['maincam_31',['mainCam',['../class_flip_camera.html#aee43d0af70acbb5b29139939f37accc6',1,'FlipCamera.mainCam()'],['../class_scene_handler.html#a8ef1b858b19bb36707ed5f45bb862aca',1,'SceneHandler.mainCam()']]], ['mat_32',['mat',['../class_clipping_cyllinder.html#a6a271f7c7125d29c5fed73ecff82b023',1,'ClippingCyllinder']]] ];
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var babelPluginFlowReactPropTypes_proptype_MarkSpec = require('./Types').babelPluginFlowReactPropTypes_proptype_MarkSpec || require('prop-types').any; var TextSuperMarkSpec = { parseDOM: [{ tag: 'sup' }, { style: 'vertical-align', getAttrs: function getAttrs(value) { return value === 'super' && null; } }], toDOM: function toDOM() { return ['sup', 0]; } }; exports.default = TextSuperMarkSpec;
// const { ObjectId } = require('bson'); const mongoose = require('mongoose'); const Schema = mongoose.Schema; const userSchema = new Schema({ fullname: { type: String, required: true }, email: { type: String, required: true }, password: { type: String, required: true }, username: { type: String, required: true, unique: true }, profilePictue: { type: String }, private:{ type:Boolean, default:false }, recivedRequestedFollows:[{ type:Schema.Types.ObjectId, ref:"User" }], sentFollowRequests:[{ type:Schema.Types.ObjectId, ref:"User" }], bio: { type: String }, city: { type: String }, followings: [ { type: Schema.Types.ObjectId, ref: "User" } ], followers: [ { type: Schema.Types.ObjectId, ref: "User" } ], tweets:[{ type:Schema.Types.ObjectId, ref:"Tweet" }], reTweets:[{ type:Schema.Types.ObjectId, ref:"Tweet" }], replies:[{ type:Schema.Types.ObjectId, ref:"Reply" }], chats:[{ chatId:{ type: Schema.Types.ObjectId, ref: "Chat" } }], chatedWith:[{ type: Schema.Types.ObjectId, ref: "User" }], likes:[ { type:Schema.Types.ObjectId, ref:"Tweet" } ] }, { timestamps: true } ); module.exports = mongoose.model('User', userSchema);
// Scroll to top feature window.onload = function() { const footerY = document.getElementsByTagName("footer")[0]; const top = document.getElementsByClassName("stick-top")[0]; // Show and hide "Scroll to Top" button document.addEventListener("scroll", e => { if (window.pageYOffset + window.innerHeight > window.innerHeight + 200) { top.classList.add("show"); } else { top.classList.remove("show"); } if (window.pageYOffset + window.innerHeight > footerY.offsetTop) { top.classList.add("sticky"); } else { top.classList.remove("sticky"); } }); top.addEventListener("click", () => { scrollToTop(); }); }; let scrollAnimation; function scrollToTop() { const position = document.body.scrollTop || document.documentElement.scrollTop; if (position) { window.scrollBy(0, -Math.max(1, Math.floor(position / 15))); // Fire scroll to top scrollAnimation = requestAnimationFrame(scrollToTop); // Add event listener to mouse scroll document.addEventListener("wheel", function wheel() { // Cancel scroll to top if user scrolls the mouse wheel during animation window.cancelAnimationFrame(scrollAnimation); document.removeEventListener("wheel", wheel); }); } }
App = { web3Provider: null, contracts: {}, init: async function() { return await App.initWeb3(); }, initWeb3: async function() { if (typeof web3 !== 'undefined') { App.web3Provider = web3.currentProvider; web3 = new Web3(web3.currentProvider); } else { App.web3Provider = new Web3.providers.HttpProvider('http://127.0.0.1:8545'); web3 = new Web3(App.web3Provider); } return App.initContract(); }, initContract: function() { var json = './control.json'; $.getJSON(json, function(data) { App.contracts.Control = TruffleContract(data); App.contracts.Control.setProvider(App.web3Provider); }); return App.bindEvents(); }, bindEvents: function() { //$(document).on('click', '.btn-adopt', App.handleAdopt); $('#create').on('click', '#create',App.create); $('#hadAccount').on('click', App.hadAccount); }, create: function() { var controller; web3.eth.getAccounts(function(error, accounts) { if (error) { console.log(error); } var account = accounts[0]; App.contracts.Control.deployed().then(function(instance) { controller = instance; if ($("input[name='accountType']:checked").val() == "p") { console.log("Create Patient Account"); return controller.createPatient($('#name').val(), parseInt($('#age').val()), parseInt($('#gender').val()), {from: account}); } else { console.log("Create Doctor Account"); return controller.createDoctor($('#name').val(), parseInt($('#age').val()), parseInt($('#gender').val()), {from: account}); } }).then(function(result) { console.log(result); }).catch(function(err) { console.log(err.message); }); }); }, hadAccount: function() { if ($("input[name='accountType']:checked").val() == "p") { console.log("Had Patient Account"); $('#inter-patient').attr('style', 'display:block'); $('#inter-doctor').attr('style', 'display:none'); $('#approve').on('click', App.approve); $('#disapprove').on('click', App.disapprove); } else { console.log("Had Doctor Account"); $('#inter-doctor').attr('style', 'display:block'); $('#inter-patient').attr('style', 'display:none'); $('#add').on('click', App.addrecord); } }, approve: function() { var controller; web3.eth.getAccounts(function(error, accounts) { if (error) { console.log(error); } var account = accounts[0]; App.contracts.Control.deployed().then(function(instance) { controller = instance; return controller.giveApproval(account, $('#doctorAddress').val(), {from: account}); }).then(function(result) { console.log(result); }).catch(function(err) { console.log(err.message); }) }); }, disapprove: function() { var controller; web3.eth.getAccounts(function(error, accounts) { if (error) { console.log(error); } var account = accounts[0]; App.contracts.Control.deployed().then(function(instance) { controller = instance; return controller.cancelApproval(account, $('#doctorAddress').val(), {from: account}); }).then(function(result) { console.log(result); }).catch(function(err) { console.log(err.message); }) }); }, addrecord: function() { var controller; web3.eth.getAccounts(function(error, accounts) { if (error) { console.log(error); } var account = accounts[0]; App.contracts.Control.deployed().then(function(instance) { controller = instance; return controller.addRecord($('#patientAddress').val(), account, $('#symtom').val(), $('#diagnosis').val(), {from: account}); }).then(function(result) { console.log(result); }).catch(function(err) { console.log(err.message); }) }); } }; $(window).on('load', function() { App.init(); });
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } require('proxy-polyfill'); var reselect = require('reselect'); var uuid = _interopDefault(require('uuid/v4')); const WINDOW_FOCUSED = 'WINDOW_FOCUSED'; const DAEMON_READY = 'DAEMON_READY'; const DAEMON_VERSION_MATCH = 'DAEMON_VERSION_MATCH'; const DAEMON_VERSION_MISMATCH = 'DAEMON_VERSION_MISMATCH'; const VOLUME_CHANGED = 'VOLUME_CHANGED'; // Navigation const CHANGE_AFTER_AUTH_PATH = 'CHANGE_AFTER_AUTH_PATH'; const WINDOW_SCROLLED = 'WINDOW_SCROLLED'; const HISTORY_NAVIGATE = 'HISTORY_NAVIGATE'; // Upgrades const UPGRADE_CANCELLED = 'UPGRADE_CANCELLED'; const DOWNLOAD_UPGRADE = 'DOWNLOAD_UPGRADE'; const UPGRADE_DOWNLOAD_STARTED = 'UPGRADE_DOWNLOAD_STARTED'; const UPGRADE_DOWNLOAD_COMPLETED = 'UPGRADE_DOWNLOAD_COMPLETED'; const UPGRADE_DOWNLOAD_PROGRESSED = 'UPGRADE_DOWNLOAD_PROGRESSED'; const CHECK_UPGRADE_AVAILABLE = 'CHECK_UPGRADE_AVAILABLE'; const CHECK_UPGRADE_START = 'CHECK_UPGRADE_START'; const CHECK_UPGRADE_SUCCESS = 'CHECK_UPGRADE_SUCCESS'; const CHECK_UPGRADE_FAIL = 'CHECK_UPGRADE_FAIL'; const CHECK_UPGRADE_SUBSCRIBE = 'CHECK_UPGRADE_SUBSCRIBE'; const UPDATE_VERSION = 'UPDATE_VERSION'; const UPDATE_REMOTE_VERSION = 'UPDATE_REMOTE_VERSION'; const SKIP_UPGRADE = 'SKIP_UPGRADE'; const START_UPGRADE = 'START_UPGRADE'; const AUTO_UPDATE_DECLINED = 'AUTO_UPDATE_DECLINED'; const AUTO_UPDATE_DOWNLOADED = 'AUTO_UPDATE_DOWNLOADED'; const CLEAR_UPGRADE_TIMER = 'CLEAR_UPGRADE_TIMER'; // Wallet const GET_NEW_ADDRESS_STARTED = 'GET_NEW_ADDRESS_STARTED'; const GET_NEW_ADDRESS_COMPLETED = 'GET_NEW_ADDRESS_COMPLETED'; const FETCH_TRANSACTIONS_STARTED = 'FETCH_TRANSACTIONS_STARTED'; const FETCH_TRANSACTIONS_COMPLETED = 'FETCH_TRANSACTIONS_COMPLETED'; const FETCH_SUPPORTS_STARTED = 'FETCH_SUPPORTS_STARTED'; const FETCH_SUPPORTS_COMPLETED = 'FETCH_SUPPORTS_COMPLETED'; const ABANDON_SUPPORT_STARTED = 'ABANDON_SUPPORT_STARTED'; const ABANDON_SUPPORT_COMPLETED = 'ABANDON_SUPPORT_COMPLETED'; const UPDATE_BALANCE = 'UPDATE_BALANCE'; const UPDATE_TOTAL_BALANCE = 'UPDATE_TOTAL_BALANCE'; const CHECK_ADDRESS_IS_MINE_STARTED = 'CHECK_ADDRESS_IS_MINE_STARTED'; const CHECK_ADDRESS_IS_MINE_COMPLETED = 'CHECK_ADDRESS_IS_MINE_COMPLETED'; const SEND_TRANSACTION_STARTED = 'SEND_TRANSACTION_STARTED'; const SEND_TRANSACTION_COMPLETED = 'SEND_TRANSACTION_COMPLETED'; const SEND_TRANSACTION_FAILED = 'SEND_TRANSACTION_FAILED'; const SUPPORT_TRANSACTION_STARTED = 'SUPPORT_TRANSACTION_STARTED'; const SUPPORT_TRANSACTION_COMPLETED = 'SUPPORT_TRANSACTION_COMPLETED'; const SUPPORT_TRANSACTION_FAILED = 'SUPPORT_TRANSACTION_FAILED'; const WALLET_ENCRYPT_START = 'WALLET_ENCRYPT_START'; const WALLET_ENCRYPT_COMPLETED = 'WALLET_ENCRYPT_COMPLETED'; const WALLET_ENCRYPT_FAILED = 'WALLET_ENCRYPT_FAILED'; const WALLET_UNLOCK_START = 'WALLET_UNLOCK_START'; const WALLET_UNLOCK_COMPLETED = 'WALLET_UNLOCK_COMPLETED'; const WALLET_UNLOCK_FAILED = 'WALLET_UNLOCK_FAILED'; const WALLET_DECRYPT_START = 'WALLET_DECRYPT_START'; const WALLET_DECRYPT_COMPLETED = 'WALLET_DECRYPT_COMPLETED'; const WALLET_DECRYPT_FAILED = 'WALLET_DECRYPT_FAILED'; const WALLET_LOCK_START = 'WALLET_LOCK_START'; const WALLET_LOCK_COMPLETED = 'WALLET_LOCK_COMPLETED'; const WALLET_LOCK_FAILED = 'WALLET_LOCK_FAILED'; const WALLET_STATUS_START = 'WALLET_STATUS_START'; const WALLET_STATUS_COMPLETED = 'WALLET_STATUS_COMPLETED'; const SET_TRANSACTION_LIST_FILTER = 'SET_TRANSACTION_LIST_FILTER'; const UPDATE_CURRENT_HEIGHT = 'UPDATE_CURRENT_HEIGHT'; const SET_DRAFT_TRANSACTION_AMOUNT = 'SET_DRAFT_TRANSACTION_AMOUNT'; const SET_DRAFT_TRANSACTION_ADDRESS = 'SET_DRAFT_TRANSACTION_ADDRESS'; // Claims const RESOLVE_URIS_STARTED = 'RESOLVE_URIS_STARTED'; const RESOLVE_URIS_COMPLETED = 'RESOLVE_URIS_COMPLETED'; const FETCH_CHANNEL_CLAIMS_STARTED = 'FETCH_CHANNEL_CLAIMS_STARTED'; const FETCH_CHANNEL_CLAIMS_COMPLETED = 'FETCH_CHANNEL_CLAIMS_COMPLETED'; const FETCH_CLAIM_LIST_MINE_STARTED = 'FETCH_CLAIM_LIST_MINE_STARTED'; const FETCH_CLAIM_LIST_MINE_COMPLETED = 'FETCH_CLAIM_LIST_MINE_COMPLETED'; const ABANDON_CLAIM_STARTED = 'ABANDON_CLAIM_STARTED'; const ABANDON_CLAIM_SUCCEEDED = 'ABANDON_CLAIM_SUCCEEDED'; const FETCH_CHANNEL_LIST_STARTED = 'FETCH_CHANNEL_LIST_STARTED'; const FETCH_CHANNEL_LIST_COMPLETED = 'FETCH_CHANNEL_LIST_COMPLETED'; const CREATE_CHANNEL_STARTED = 'CREATE_CHANNEL_STARTED'; const CREATE_CHANNEL_COMPLETED = 'CREATE_CHANNEL_COMPLETED'; const CREATE_CHANNEL_FAILED = 'CREATE_CHANNEL_FAILED'; const PUBLISH_STARTED = 'PUBLISH_STARTED'; const PUBLISH_COMPLETED = 'PUBLISH_COMPLETED'; const PUBLISH_FAILED = 'PUBLISH_FAILED'; const SET_PLAYING_URI = 'SET_PLAYING_URI'; const SET_CONTENT_POSITION = 'SET_CONTENT_POSITION'; const SET_CONTENT_LAST_VIEWED = 'SET_CONTENT_LAST_VIEWED'; const CLEAR_CONTENT_HISTORY_URI = 'CLEAR_CONTENT_HISTORY_URI'; const CLEAR_CONTENT_HISTORY_ALL = 'CLEAR_CONTENT_HISTORY_ALL'; const CLAIM_SEARCH_STARTED = 'CLAIM_SEARCH_STARTED'; const CLAIM_SEARCH_COMPLETED = 'CLAIM_SEARCH_COMPLETED'; const CLAIM_SEARCH_FAILED = 'CLAIM_SEARCH_FAILED'; // Files const FILE_LIST_STARTED = 'FILE_LIST_STARTED'; const FILE_LIST_SUCCEEDED = 'FILE_LIST_SUCCEEDED'; const FETCH_FILE_INFO_STARTED = 'FETCH_FILE_INFO_STARTED'; const FETCH_FILE_INFO_COMPLETED = 'FETCH_FILE_INFO_COMPLETED'; const LOADING_VIDEO_STARTED = 'LOADING_VIDEO_STARTED'; const LOADING_VIDEO_COMPLETED = 'LOADING_VIDEO_COMPLETED'; const LOADING_VIDEO_FAILED = 'LOADING_VIDEO_FAILED'; const DOWNLOADING_STARTED = 'DOWNLOADING_STARTED'; const DOWNLOADING_PROGRESSED = 'DOWNLOADING_PROGRESSED'; const DOWNLOADING_COMPLETED = 'DOWNLOADING_COMPLETED'; const DOWNLOADING_CANCELED = 'DOWNLOADING_CANCELED'; const PLAY_VIDEO_STARTED = 'PLAY_VIDEO_STARTED'; const FETCH_AVAILABILITY_STARTED = 'FETCH_AVAILABILITY_STARTED'; const FETCH_AVAILABILITY_COMPLETED = 'FETCH_AVAILABILITY_COMPLETED'; const FILE_DELETE = 'FILE_DELETE'; const SET_FILE_LIST_SORT = 'SET_FILE_LIST_SORT'; const PURCHASE_URI_STARTED = 'PURCHASE_URI_STARTED'; const PURCHASE_URI_COMPLETED = 'PURCHASE_URI_COMPLETED'; const PURCHASE_URI_FAILED = 'PURCHASE_URI_FAILED'; const DELETE_PURCHASED_URI = 'DELETE_PURCHASED_URI'; const LOADING_FILE_STARTED = 'LOADING_FILE_STARTED'; const LOADING_FILE_COMPLETED = 'LOADING_FILE_COMPLETED'; const LOADING_FILE_FAILED = 'LOADING_FILE_FAILED'; // Search const SEARCH_START = 'SEARCH_START'; const SEARCH_SUCCESS = 'SEARCH_SUCCESS'; const SEARCH_FAIL = 'SEARCH_FAIL'; const UPDATE_SEARCH_QUERY = 'UPDATE_SEARCH_QUERY'; const UPDATE_SEARCH_OPTIONS = 'UPDATE_SEARCH_OPTIONS'; const UPDATE_SEARCH_SUGGESTIONS = 'UPDATE_SEARCH_SUGGESTIONS'; const SEARCH_FOCUS = 'SEARCH_FOCUS'; const SEARCH_BLUR = 'SEARCH_BLUR'; // Settings const DAEMON_SETTINGS_RECEIVED = 'DAEMON_SETTINGS_RECEIVED'; const CLIENT_SETTING_CHANGED = 'CLIENT_SETTING_CHANGED'; const UPDATE_IS_NIGHT = 'UPDATE_IS_NIGHT'; // User const AUTHENTICATION_STARTED = 'AUTHENTICATION_STARTED'; const AUTHENTICATION_SUCCESS = 'AUTHENTICATION_SUCCESS'; const AUTHENTICATION_FAILURE = 'AUTHENTICATION_FAILURE'; const USER_EMAIL_DECLINE = 'USER_EMAIL_DECLINE'; const USER_EMAIL_NEW_STARTED = 'USER_EMAIL_NEW_STARTED'; const USER_EMAIL_NEW_SUCCESS = 'USER_EMAIL_NEW_SUCCESS'; const USER_EMAIL_NEW_EXISTS = 'USER_EMAIL_NEW_EXISTS'; const USER_EMAIL_NEW_FAILURE = 'USER_EMAIL_NEW_FAILURE'; const USER_EMAIL_VERIFY_SET = 'USER_EMAIL_VERIFY_SET'; const USER_EMAIL_VERIFY_STARTED = 'USER_EMAIL_VERIFY_STARTED'; const USER_EMAIL_VERIFY_SUCCESS = 'USER_EMAIL_VERIFY_SUCCESS'; const USER_EMAIL_VERIFY_FAILURE = 'USER_EMAIL_VERIFY_FAILURE'; const USER_EMAIL_VERIFY_RETRY = 'USER_EMAIL_VERIFY_RETRY'; const USER_PHONE_RESET = 'USER_PHONE_RESET'; const USER_PHONE_NEW_STARTED = 'USER_PHONE_NEW_STARTED'; const USER_PHONE_NEW_SUCCESS = 'USER_PHONE_NEW_SUCCESS'; const USER_PHONE_NEW_FAILURE = 'USER_PHONE_NEW_FAILURE'; const USER_PHONE_VERIFY_STARTED = 'USER_PHONE_VERIFY_STARTED'; const USER_PHONE_VERIFY_SUCCESS = 'USER_PHONE_VERIFY_SUCCESS'; const USER_PHONE_VERIFY_FAILURE = 'USER_PHONE_VERIFY_FAILURE'; const USER_IDENTITY_VERIFY_STARTED = 'USER_IDENTITY_VERIFY_STARTED'; const USER_IDENTITY_VERIFY_SUCCESS = 'USER_IDENTITY_VERIFY_SUCCESS'; const USER_IDENTITY_VERIFY_FAILURE = 'USER_IDENTITY_VERIFY_FAILURE'; const USER_FETCH_STARTED = 'USER_FETCH_STARTED'; const USER_FETCH_SUCCESS = 'USER_FETCH_SUCCESS'; const USER_FETCH_FAILURE = 'USER_FETCH_FAILURE'; const USER_INVITE_STATUS_FETCH_STARTED = 'USER_INVITE_STATUS_FETCH_STARTED'; const USER_INVITE_STATUS_FETCH_SUCCESS = 'USER_INVITE_STATUS_FETCH_SUCCESS'; const USER_INVITE_STATUS_FETCH_FAILURE = 'USER_INVITE_STATUS_FETCH_FAILURE'; const USER_INVITE_NEW_STARTED = 'USER_INVITE_NEW_STARTED'; const USER_INVITE_NEW_SUCCESS = 'USER_INVITE_NEW_SUCCESS'; const USER_INVITE_NEW_FAILURE = 'USER_INVITE_NEW_FAILURE'; const FETCH_ACCESS_TOKEN_SUCCESS = 'FETCH_ACCESS_TOKEN_SUCCESS'; // Rewards const FETCH_REWARDS_STARTED = 'FETCH_REWARDS_STARTED'; const FETCH_REWARDS_COMPLETED = 'FETCH_REWARDS_COMPLETED'; const CLAIM_REWARD_STARTED = 'CLAIM_REWARD_STARTED'; const CLAIM_REWARD_SUCCESS = 'CLAIM_REWARD_SUCCESS'; const CLAIM_REWARD_FAILURE = 'CLAIM_REWARD_FAILURE'; const CLAIM_REWARD_CLEAR_ERROR = 'CLAIM_REWARD_CLEAR_ERROR'; const FETCH_REWARD_CONTENT_COMPLETED = 'FETCH_REWARD_CONTENT_COMPLETED'; // Language const DOWNLOAD_LANGUAGE_SUCCEEDED = 'DOWNLOAD_LANGUAGE_SUCCEEDED'; const DOWNLOAD_LANGUAGE_FAILED = 'DOWNLOAD_LANGUAGE_FAILED'; // Subscriptions const CHANNEL_SUBSCRIBE = 'CHANNEL_SUBSCRIBE'; const CHANNEL_UNSUBSCRIBE = 'CHANNEL_UNSUBSCRIBE'; const HAS_FETCHED_SUBSCRIPTIONS = 'HAS_FETCHED_SUBSCRIPTIONS'; const SET_SUBSCRIPTION_LATEST = 'SET_SUBSCRIPTION_LATEST'; const SET_SUBSCRIPTION_NOTIFICATION = 'SET_SUBSCRIPTION_NOTIFICATION'; const SET_SUBSCRIPTION_NOTIFICATIONS = 'SET_SUBSCRIPTION_NOTIFICATIONS'; const CHECK_SUBSCRIPTION_STARTED = 'CHECK_SUBSCRIPTION_STARTED'; const CHECK_SUBSCRIPTION_COMPLETED = 'CHECK_SUBSCRIPTION_COMPLETED'; const CHECK_SUBSCRIPTIONS_SUBSCRIBE = 'CHECK_SUBSCRIPTIONS_SUBSCRIBE'; // Publishing const CLEAR_PUBLISH = 'CLEAR_PUBLISH'; const UPDATE_PUBLISH_FORM = 'UPDATE_PUBLISH_FORM'; const PUBLISH_START = 'PUBLISH_START'; const PUBLISH_SUCCESS = 'PUBLISH_SUCCESS'; const PUBLISH_FAIL = 'PUBLISH_FAIL'; const CLEAR_PUBLISH_ERROR = 'CLEAR_PUBLISH_ERROR'; const REMOVE_PENDING_PUBLISH = 'REMOVE_PENDING_PUBLISH'; const DO_PREPARE_EDIT = 'DO_PREPARE_EDIT'; // Notifications const CREATE_NOTIFICATION = 'CREATE_NOTIFICATION'; const EDIT_NOTIFICATION = 'EDIT_NOTIFICATION'; const DELETE_NOTIFICATION = 'DELETE_NOTIFICATION'; const DISMISS_NOTIFICATION = 'DISMISS_NOTIFICATION'; const CREATE_TOAST = 'CREATE_TOAST'; const DISMISS_TOAST = 'DISMISS_TOAST'; const CREATE_ERROR = 'CREATE_ERROR'; const DISMISS_ERROR = 'DISMISS_ERROR'; const FETCH_DATE = 'FETCH_DATE'; // Cost info const FETCH_COST_INFO_STARTED = 'FETCH_COST_INFO_STARTED'; const FETCH_COST_INFO_COMPLETED = 'FETCH_COST_INFO_COMPLETED'; const FETCH_COST_INFO_FAILED = 'FETCH_COST_INFO_FAILED'; // Tags const TOGGLE_TAG_FOLLOW = 'TOGGLE_TAG_FOLLOW'; const TAG_ADD = 'TAG_ADD'; const TAG_DELETE = 'TAG_DELETE'; var action_types = /*#__PURE__*/Object.freeze({ WINDOW_FOCUSED: WINDOW_FOCUSED, DAEMON_READY: DAEMON_READY, DAEMON_VERSION_MATCH: DAEMON_VERSION_MATCH, DAEMON_VERSION_MISMATCH: DAEMON_VERSION_MISMATCH, VOLUME_CHANGED: VOLUME_CHANGED, CHANGE_AFTER_AUTH_PATH: CHANGE_AFTER_AUTH_PATH, WINDOW_SCROLLED: WINDOW_SCROLLED, HISTORY_NAVIGATE: HISTORY_NAVIGATE, UPGRADE_CANCELLED: UPGRADE_CANCELLED, DOWNLOAD_UPGRADE: DOWNLOAD_UPGRADE, UPGRADE_DOWNLOAD_STARTED: UPGRADE_DOWNLOAD_STARTED, UPGRADE_DOWNLOAD_COMPLETED: UPGRADE_DOWNLOAD_COMPLETED, UPGRADE_DOWNLOAD_PROGRESSED: UPGRADE_DOWNLOAD_PROGRESSED, CHECK_UPGRADE_AVAILABLE: CHECK_UPGRADE_AVAILABLE, CHECK_UPGRADE_START: CHECK_UPGRADE_START, CHECK_UPGRADE_SUCCESS: CHECK_UPGRADE_SUCCESS, CHECK_UPGRADE_FAIL: CHECK_UPGRADE_FAIL, CHECK_UPGRADE_SUBSCRIBE: CHECK_UPGRADE_SUBSCRIBE, UPDATE_VERSION: UPDATE_VERSION, UPDATE_REMOTE_VERSION: UPDATE_REMOTE_VERSION, SKIP_UPGRADE: SKIP_UPGRADE, START_UPGRADE: START_UPGRADE, AUTO_UPDATE_DECLINED: AUTO_UPDATE_DECLINED, AUTO_UPDATE_DOWNLOADED: AUTO_UPDATE_DOWNLOADED, CLEAR_UPGRADE_TIMER: CLEAR_UPGRADE_TIMER, GET_NEW_ADDRESS_STARTED: GET_NEW_ADDRESS_STARTED, GET_NEW_ADDRESS_COMPLETED: GET_NEW_ADDRESS_COMPLETED, FETCH_TRANSACTIONS_STARTED: FETCH_TRANSACTIONS_STARTED, FETCH_TRANSACTIONS_COMPLETED: FETCH_TRANSACTIONS_COMPLETED, FETCH_SUPPORTS_STARTED: FETCH_SUPPORTS_STARTED, FETCH_SUPPORTS_COMPLETED: FETCH_SUPPORTS_COMPLETED, ABANDON_SUPPORT_STARTED: ABANDON_SUPPORT_STARTED, ABANDON_SUPPORT_COMPLETED: ABANDON_SUPPORT_COMPLETED, UPDATE_BALANCE: UPDATE_BALANCE, UPDATE_TOTAL_BALANCE: UPDATE_TOTAL_BALANCE, CHECK_ADDRESS_IS_MINE_STARTED: CHECK_ADDRESS_IS_MINE_STARTED, CHECK_ADDRESS_IS_MINE_COMPLETED: CHECK_ADDRESS_IS_MINE_COMPLETED, SEND_TRANSACTION_STARTED: SEND_TRANSACTION_STARTED, SEND_TRANSACTION_COMPLETED: SEND_TRANSACTION_COMPLETED, SEND_TRANSACTION_FAILED: SEND_TRANSACTION_FAILED, SUPPORT_TRANSACTION_STARTED: SUPPORT_TRANSACTION_STARTED, SUPPORT_TRANSACTION_COMPLETED: SUPPORT_TRANSACTION_COMPLETED, SUPPORT_TRANSACTION_FAILED: SUPPORT_TRANSACTION_FAILED, WALLET_ENCRYPT_START: WALLET_ENCRYPT_START, WALLET_ENCRYPT_COMPLETED: WALLET_ENCRYPT_COMPLETED, WALLET_ENCRYPT_FAILED: WALLET_ENCRYPT_FAILED, WALLET_UNLOCK_START: WALLET_UNLOCK_START, WALLET_UNLOCK_COMPLETED: WALLET_UNLOCK_COMPLETED, WALLET_UNLOCK_FAILED: WALLET_UNLOCK_FAILED, WALLET_DECRYPT_START: WALLET_DECRYPT_START, WALLET_DECRYPT_COMPLETED: WALLET_DECRYPT_COMPLETED, WALLET_DECRYPT_FAILED: WALLET_DECRYPT_FAILED, WALLET_LOCK_START: WALLET_LOCK_START, WALLET_LOCK_COMPLETED: WALLET_LOCK_COMPLETED, WALLET_LOCK_FAILED: WALLET_LOCK_FAILED, WALLET_STATUS_START: WALLET_STATUS_START, WALLET_STATUS_COMPLETED: WALLET_STATUS_COMPLETED, SET_TRANSACTION_LIST_FILTER: SET_TRANSACTION_LIST_FILTER, UPDATE_CURRENT_HEIGHT: UPDATE_CURRENT_HEIGHT, SET_DRAFT_TRANSACTION_AMOUNT: SET_DRAFT_TRANSACTION_AMOUNT, SET_DRAFT_TRANSACTION_ADDRESS: SET_DRAFT_TRANSACTION_ADDRESS, RESOLVE_URIS_STARTED: RESOLVE_URIS_STARTED, RESOLVE_URIS_COMPLETED: RESOLVE_URIS_COMPLETED, FETCH_CHANNEL_CLAIMS_STARTED: FETCH_CHANNEL_CLAIMS_STARTED, FETCH_CHANNEL_CLAIMS_COMPLETED: FETCH_CHANNEL_CLAIMS_COMPLETED, FETCH_CLAIM_LIST_MINE_STARTED: FETCH_CLAIM_LIST_MINE_STARTED, FETCH_CLAIM_LIST_MINE_COMPLETED: FETCH_CLAIM_LIST_MINE_COMPLETED, ABANDON_CLAIM_STARTED: ABANDON_CLAIM_STARTED, ABANDON_CLAIM_SUCCEEDED: ABANDON_CLAIM_SUCCEEDED, FETCH_CHANNEL_LIST_STARTED: FETCH_CHANNEL_LIST_STARTED, FETCH_CHANNEL_LIST_COMPLETED: FETCH_CHANNEL_LIST_COMPLETED, CREATE_CHANNEL_STARTED: CREATE_CHANNEL_STARTED, CREATE_CHANNEL_COMPLETED: CREATE_CHANNEL_COMPLETED, CREATE_CHANNEL_FAILED: CREATE_CHANNEL_FAILED, PUBLISH_STARTED: PUBLISH_STARTED, PUBLISH_COMPLETED: PUBLISH_COMPLETED, PUBLISH_FAILED: PUBLISH_FAILED, SET_PLAYING_URI: SET_PLAYING_URI, SET_CONTENT_POSITION: SET_CONTENT_POSITION, SET_CONTENT_LAST_VIEWED: SET_CONTENT_LAST_VIEWED, CLEAR_CONTENT_HISTORY_URI: CLEAR_CONTENT_HISTORY_URI, CLEAR_CONTENT_HISTORY_ALL: CLEAR_CONTENT_HISTORY_ALL, CLAIM_SEARCH_STARTED: CLAIM_SEARCH_STARTED, CLAIM_SEARCH_COMPLETED: CLAIM_SEARCH_COMPLETED, CLAIM_SEARCH_FAILED: CLAIM_SEARCH_FAILED, FILE_LIST_STARTED: FILE_LIST_STARTED, FILE_LIST_SUCCEEDED: FILE_LIST_SUCCEEDED, FETCH_FILE_INFO_STARTED: FETCH_FILE_INFO_STARTED, FETCH_FILE_INFO_COMPLETED: FETCH_FILE_INFO_COMPLETED, LOADING_VIDEO_STARTED: LOADING_VIDEO_STARTED, LOADING_VIDEO_COMPLETED: LOADING_VIDEO_COMPLETED, LOADING_VIDEO_FAILED: LOADING_VIDEO_FAILED, DOWNLOADING_STARTED: DOWNLOADING_STARTED, DOWNLOADING_PROGRESSED: DOWNLOADING_PROGRESSED, DOWNLOADING_COMPLETED: DOWNLOADING_COMPLETED, DOWNLOADING_CANCELED: DOWNLOADING_CANCELED, PLAY_VIDEO_STARTED: PLAY_VIDEO_STARTED, FETCH_AVAILABILITY_STARTED: FETCH_AVAILABILITY_STARTED, FETCH_AVAILABILITY_COMPLETED: FETCH_AVAILABILITY_COMPLETED, FILE_DELETE: FILE_DELETE, SET_FILE_LIST_SORT: SET_FILE_LIST_SORT, PURCHASE_URI_STARTED: PURCHASE_URI_STARTED, PURCHASE_URI_COMPLETED: PURCHASE_URI_COMPLETED, PURCHASE_URI_FAILED: PURCHASE_URI_FAILED, DELETE_PURCHASED_URI: DELETE_PURCHASED_URI, LOADING_FILE_STARTED: LOADING_FILE_STARTED, LOADING_FILE_COMPLETED: LOADING_FILE_COMPLETED, LOADING_FILE_FAILED: LOADING_FILE_FAILED, SEARCH_START: SEARCH_START, SEARCH_SUCCESS: SEARCH_SUCCESS, SEARCH_FAIL: SEARCH_FAIL, UPDATE_SEARCH_QUERY: UPDATE_SEARCH_QUERY, UPDATE_SEARCH_OPTIONS: UPDATE_SEARCH_OPTIONS, UPDATE_SEARCH_SUGGESTIONS: UPDATE_SEARCH_SUGGESTIONS, SEARCH_FOCUS: SEARCH_FOCUS, SEARCH_BLUR: SEARCH_BLUR, DAEMON_SETTINGS_RECEIVED: DAEMON_SETTINGS_RECEIVED, CLIENT_SETTING_CHANGED: CLIENT_SETTING_CHANGED, UPDATE_IS_NIGHT: UPDATE_IS_NIGHT, AUTHENTICATION_STARTED: AUTHENTICATION_STARTED, AUTHENTICATION_SUCCESS: AUTHENTICATION_SUCCESS, AUTHENTICATION_FAILURE: AUTHENTICATION_FAILURE, USER_EMAIL_DECLINE: USER_EMAIL_DECLINE, USER_EMAIL_NEW_STARTED: USER_EMAIL_NEW_STARTED, USER_EMAIL_NEW_SUCCESS: USER_EMAIL_NEW_SUCCESS, USER_EMAIL_NEW_EXISTS: USER_EMAIL_NEW_EXISTS, USER_EMAIL_NEW_FAILURE: USER_EMAIL_NEW_FAILURE, USER_EMAIL_VERIFY_SET: USER_EMAIL_VERIFY_SET, USER_EMAIL_VERIFY_STARTED: USER_EMAIL_VERIFY_STARTED, USER_EMAIL_VERIFY_SUCCESS: USER_EMAIL_VERIFY_SUCCESS, USER_EMAIL_VERIFY_FAILURE: USER_EMAIL_VERIFY_FAILURE, USER_EMAIL_VERIFY_RETRY: USER_EMAIL_VERIFY_RETRY, USER_PHONE_RESET: USER_PHONE_RESET, USER_PHONE_NEW_STARTED: USER_PHONE_NEW_STARTED, USER_PHONE_NEW_SUCCESS: USER_PHONE_NEW_SUCCESS, USER_PHONE_NEW_FAILURE: USER_PHONE_NEW_FAILURE, USER_PHONE_VERIFY_STARTED: USER_PHONE_VERIFY_STARTED, USER_PHONE_VERIFY_SUCCESS: USER_PHONE_VERIFY_SUCCESS, USER_PHONE_VERIFY_FAILURE: USER_PHONE_VERIFY_FAILURE, USER_IDENTITY_VERIFY_STARTED: USER_IDENTITY_VERIFY_STARTED, USER_IDENTITY_VERIFY_SUCCESS: USER_IDENTITY_VERIFY_SUCCESS, USER_IDENTITY_VERIFY_FAILURE: USER_IDENTITY_VERIFY_FAILURE, USER_FETCH_STARTED: USER_FETCH_STARTED, USER_FETCH_SUCCESS: USER_FETCH_SUCCESS, USER_FETCH_FAILURE: USER_FETCH_FAILURE, USER_INVITE_STATUS_FETCH_STARTED: USER_INVITE_STATUS_FETCH_STARTED, USER_INVITE_STATUS_FETCH_SUCCESS: USER_INVITE_STATUS_FETCH_SUCCESS, USER_INVITE_STATUS_FETCH_FAILURE: USER_INVITE_STATUS_FETCH_FAILURE, USER_INVITE_NEW_STARTED: USER_INVITE_NEW_STARTED, USER_INVITE_NEW_SUCCESS: USER_INVITE_NEW_SUCCESS, USER_INVITE_NEW_FAILURE: USER_INVITE_NEW_FAILURE, FETCH_ACCESS_TOKEN_SUCCESS: FETCH_ACCESS_TOKEN_SUCCESS, FETCH_REWARDS_STARTED: FETCH_REWARDS_STARTED, FETCH_REWARDS_COMPLETED: FETCH_REWARDS_COMPLETED, CLAIM_REWARD_STARTED: CLAIM_REWARD_STARTED, CLAIM_REWARD_SUCCESS: CLAIM_REWARD_SUCCESS, CLAIM_REWARD_FAILURE: CLAIM_REWARD_FAILURE, CLAIM_REWARD_CLEAR_ERROR: CLAIM_REWARD_CLEAR_ERROR, FETCH_REWARD_CONTENT_COMPLETED: FETCH_REWARD_CONTENT_COMPLETED, DOWNLOAD_LANGUAGE_SUCCEEDED: DOWNLOAD_LANGUAGE_SUCCEEDED, DOWNLOAD_LANGUAGE_FAILED: DOWNLOAD_LANGUAGE_FAILED, CHANNEL_SUBSCRIBE: CHANNEL_SUBSCRIBE, CHANNEL_UNSUBSCRIBE: CHANNEL_UNSUBSCRIBE, HAS_FETCHED_SUBSCRIPTIONS: HAS_FETCHED_SUBSCRIPTIONS, SET_SUBSCRIPTION_LATEST: SET_SUBSCRIPTION_LATEST, SET_SUBSCRIPTION_NOTIFICATION: SET_SUBSCRIPTION_NOTIFICATION, SET_SUBSCRIPTION_NOTIFICATIONS: SET_SUBSCRIPTION_NOTIFICATIONS, CHECK_SUBSCRIPTION_STARTED: CHECK_SUBSCRIPTION_STARTED, CHECK_SUBSCRIPTION_COMPLETED: CHECK_SUBSCRIPTION_COMPLETED, CHECK_SUBSCRIPTIONS_SUBSCRIBE: CHECK_SUBSCRIPTIONS_SUBSCRIBE, CLEAR_PUBLISH: CLEAR_PUBLISH, UPDATE_PUBLISH_FORM: UPDATE_PUBLISH_FORM, PUBLISH_START: PUBLISH_START, PUBLISH_SUCCESS: PUBLISH_SUCCESS, PUBLISH_FAIL: PUBLISH_FAIL, CLEAR_PUBLISH_ERROR: CLEAR_PUBLISH_ERROR, REMOVE_PENDING_PUBLISH: REMOVE_PENDING_PUBLISH, DO_PREPARE_EDIT: DO_PREPARE_EDIT, CREATE_NOTIFICATION: CREATE_NOTIFICATION, EDIT_NOTIFICATION: EDIT_NOTIFICATION, DELETE_NOTIFICATION: DELETE_NOTIFICATION, DISMISS_NOTIFICATION: DISMISS_NOTIFICATION, CREATE_TOAST: CREATE_TOAST, DISMISS_TOAST: DISMISS_TOAST, CREATE_ERROR: CREATE_ERROR, DISMISS_ERROR: DISMISS_ERROR, FETCH_DATE: FETCH_DATE, FETCH_COST_INFO_STARTED: FETCH_COST_INFO_STARTED, FETCH_COST_INFO_COMPLETED: FETCH_COST_INFO_COMPLETED, FETCH_COST_INFO_FAILED: FETCH_COST_INFO_FAILED, TOGGLE_TAG_FOLLOW: TOGGLE_TAG_FOLLOW, TAG_ADD: TAG_ADD, TAG_DELETE: TAG_DELETE }); const API_DOWN = 'apiDown'; const READY = 'ready'; const IN_PROGRESS = 'inProgress'; const COMPLETE = 'complete'; const MANUAL = 'manual'; var thumbnail_upload_statuses = /*#__PURE__*/Object.freeze({ API_DOWN: API_DOWN, READY: READY, IN_PROGRESS: IN_PROGRESS, COMPLETE: COMPLETE, MANUAL: MANUAL }); /* hardcoded names still exist for these in reducers/settings.js - only discovered when debugging */ /* Many SETTINGS are stored in the localStorage by their name - be careful about changing the value of a SETTINGS constant, as doing so can invalidate existing SETTINGS */ const CREDIT_REQUIRED_ACKNOWLEDGED = 'credit_required_acknowledged'; const NEW_USER_ACKNOWLEDGED = 'welcome_acknowledged'; const EMAIL_COLLECTION_ACKNOWLEDGED = 'email_collection_acknowledged'; const LANGUAGE = 'language'; const SHOW_NSFW = 'showNsfw'; const SHOW_UNAVAILABLE = 'showUnavailable'; const INSTANT_PURCHASE_ENABLED = 'instantPurchaseEnabled'; const INSTANT_PURCHASE_MAX = 'instantPurchaseMax'; const THEME = 'theme'; const THEMES = 'themes'; const AUTOMATIC_DARK_MODE_ENABLED = 'automaticDarkModeEnabled'; // mobile settings const BACKGROUND_PLAY_ENABLED = 'backgroundPlayEnabled'; const FOREGROUND_NOTIFICATION_ENABLED = 'foregroundNotificationEnabled'; const KEEP_DAEMON_RUNNING = 'keepDaemonRunning'; var settings = /*#__PURE__*/Object.freeze({ CREDIT_REQUIRED_ACKNOWLEDGED: CREDIT_REQUIRED_ACKNOWLEDGED, NEW_USER_ACKNOWLEDGED: NEW_USER_ACKNOWLEDGED, EMAIL_COLLECTION_ACKNOWLEDGED: EMAIL_COLLECTION_ACKNOWLEDGED, LANGUAGE: LANGUAGE, SHOW_NSFW: SHOW_NSFW, SHOW_UNAVAILABLE: SHOW_UNAVAILABLE, INSTANT_PURCHASE_ENABLED: INSTANT_PURCHASE_ENABLED, INSTANT_PURCHASE_MAX: INSTANT_PURCHASE_MAX, THEME: THEME, THEMES: THEMES, AUTOMATIC_DARK_MODE_ENABLED: AUTOMATIC_DARK_MODE_ENABLED, BACKGROUND_PLAY_ENABLED: BACKGROUND_PLAY_ENABLED, FOREGROUND_NOTIFICATION_ENABLED: FOREGROUND_NOTIFICATION_ENABLED, KEEP_DAEMON_RUNNING: KEEP_DAEMON_RUNNING }); // eslint-disable-next-line import/prefer-default-export const ALL = 'all'; const SPEND = 'spend'; const RECEIVE = 'receive'; const PUBLISH = 'publish'; const CHANNEL = 'channel'; const TIP = 'tip'; const SUPPORT = 'support'; const UPDATE = 'update'; const ABANDON = 'abandon'; var transaction_types = /*#__PURE__*/Object.freeze({ ALL: ALL, SPEND: SPEND, RECEIVE: RECEIVE, PUBLISH: PUBLISH, CHANNEL: CHANNEL, TIP: TIP, SUPPORT: SUPPORT, UPDATE: UPDATE, ABANDON: ABANDON }); const DATE_NEW = 'dateNew'; const DATE_OLD = 'dateOld'; const TITLE = 'title'; const FILENAME = 'filename'; var sort_options = /*#__PURE__*/Object.freeze({ DATE_NEW: DATE_NEW, DATE_OLD: DATE_OLD, TITLE: TITLE, FILENAME: FILENAME }); const AUTH = 'auth'; const BACKUP = 'backup'; const CHANNEL$1 = 'channel'; const DISCOVER = 'discover'; const FILE = 'file'; const DOWNLOADED = 'downloaded'; const PUBLISHED = 'published'; const GET_CREDITS = 'getcredits'; const HELP = 'help'; const INVITE = 'invite'; const PUBLISH$1 = 'publish'; const REPORT = 'report'; const REWARDS = 'rewards'; const SEARCH = 'search'; const SEND_CREDITS = 'send'; const SETTINGS = 'settings'; const SHOW = 'show'; const SUBSCRIPTIONS = 'subscriptions'; const TRANSACTION_HISTORY = 'history'; const HISTORY = 'user_history'; const WALLET = 'wallet'; var pages = /*#__PURE__*/Object.freeze({ AUTH: AUTH, BACKUP: BACKUP, CHANNEL: CHANNEL$1, DISCOVER: DISCOVER, FILE: FILE, DOWNLOADED: DOWNLOADED, PUBLISHED: PUBLISHED, GET_CREDITS: GET_CREDITS, HELP: HELP, INVITE: INVITE, PUBLISH: PUBLISH$1, REPORT: REPORT, REWARDS: REWARDS, SEARCH: SEARCH, SEND_CREDITS: SEND_CREDITS, SETTINGS: SETTINGS, SHOW: SHOW, SUBSCRIPTIONS: SUBSCRIPTIONS, TRANSACTION_HISTORY: TRANSACTION_HISTORY, HISTORY: HISTORY, WALLET: WALLET }); const SEARCH_TYPES = { FILE: 'file', CHANNEL: 'channel', SEARCH: 'search' }; const SEARCH_OPTIONS = { RESULT_COUNT: 'size', CLAIM_TYPE: 'claimType', INCLUDE_FILES: 'file', INCLUDE_CHANNELS: 'channel', INCLUDE_FILES_AND_CHANNELS: 'file,channel', MEDIA_AUDIO: 'audio', MEDIA_VIDEO: 'video', MEDIA_TEXT: 'text', MEDIA_IMAGE: 'image', MEDIA_APPLICATION: 'application' }; // const CHECK_DAEMON_STARTED_TRY_NUMBER = 200; // // Basic LBRY sdk connection config // Offers a proxy to call LBRY sdk methods // const Lbry = { isConnected: false, connectPromise: null, daemonConnectionString: 'http://localhost:5279', apiRequestHeaders: { 'Content-Type': 'application/json-rpc' }, // Allow overriding daemon connection string (e.g. to `/api/proxy` for lbryweb) setDaemonConnectionString: value => { Lbry.daemonConnectionString = value; }, setApiHeader: (key, value) => { Lbry.apiRequestHeaders = Object.assign(Lbry.apiRequestHeaders, { [key]: value }); }, unsetApiHeader: key => { Object.keys(Lbry.apiRequestHeaders).includes(key) && delete Lbry.apiRequestHeaders['key']; }, // Allow overriding Lbry methods overrides: {}, setOverride: (methodName, newMethod) => { Lbry.overrides[methodName] = newMethod; }, // Returns a human readable media type based on the content type or extension of a file that is returned by the sdk getMediaType: (contentType, extname) => { if (extname) { const formats = [[/^(mp4|m4v|webm|flv|f4v|ogv)$/i, 'video'], [/^(mp3|m4a|aac|wav|flac|ogg|opus)$/i, 'audio'], [/^(html|htm|xml|pdf|odf|doc|docx|md|markdown|txt|epub|org)$/i, 'document'], [/^(stl|obj|fbx|gcode)$/i, '3D-file']]; const res = formats.reduce((ret, testpair) => { switch (testpair[0].test(ret)) { case true: return testpair[1]; default: return ret; } }, extname); return res === extname ? 'unknown' : res; } else if (contentType) { // $FlowFixMe return (/^[^/]+/.exec(contentType)[0] ); } return 'unknown'; }, // // Lbry SDK Methods // https://lbry.tech/api/sdk // status: (params = {}) => daemonCallWithResult('status', params), stop: () => daemonCallWithResult('stop', {}), version: () => daemonCallWithResult('version', {}), // Claim fetching and manipulation resolve: params => daemonCallWithResult('resolve', params), get: params => daemonCallWithResult('get', params), publish: params => daemonCallWithResult('publish', params), claim_search: params => daemonCallWithResult('claim_search', params), claim_list: params => daemonCallWithResult('claim_list', params), channel_create: params => daemonCallWithResult('channel_create', params), channel_list: params => daemonCallWithResult('channel_list', params), stream_abandon: params => daemonCallWithResult('stream_abandon', params), channel_abandon: params => daemonCallWithResult('channel_abandon', params), support_create: params => daemonCallWithResult('support_create', params), // File fetching and manipulation file_list: (params = {}) => daemonCallWithResult('file_list', params), file_delete: (params = {}) => daemonCallWithResult('file_delete', params), file_set_status: (params = {}) => daemonCallWithResult('file_set_status', params), blob_delete: (params = {}) => daemonCallWithResult('blob_delete', params), blob_list: (params = {}) => daemonCallWithResult('blob_list', params), // Wallet utilities account_balance: (params = {}) => daemonCallWithResult('account_balance', params), account_decrypt: () => daemonCallWithResult('account_decrypt', {}), account_encrypt: (params = {}) => daemonCallWithResult('account_encrypt', params), account_unlock: (params = {}) => daemonCallWithResult('account_unlock', params), account_list: (params = {}) => daemonCallWithResult('account_list', params), account_send: (params = {}) => daemonCallWithResult('account_send', params), account_set: (params = {}) => daemonCallWithResult('account_set', params), address_is_mine: (params = {}) => daemonCallWithResult('address_is_mine', params), address_unused: (params = {}) => daemonCallWithResult('address_unused', params), transaction_list: (params = {}) => daemonCallWithResult('transaction_list', params), utxo_release: (params = {}) => daemonCallWithResult('utxo_release', params), support_abandon: (params = {}) => daemonCallWithResult('support_abandon', params), sync_hash: (params = {}) => daemonCallWithResult('sync_hash', params), sync_apply: (params = {}) => daemonCallWithResult('sync_apply', params), // Connect to the sdk connect: () => { if (Lbry.connectPromise === null) { Lbry.connectPromise = new Promise((resolve, reject) => { let tryNum = 0; // Check every half second to see if the daemon is accepting connections function checkDaemonStarted() { tryNum += 1; Lbry.status().then(resolve).catch(() => { if (tryNum <= CHECK_DAEMON_STARTED_TRY_NUMBER) { setTimeout(checkDaemonStarted, tryNum < 50 ? 400 : 1000); } else { reject(new Error('Unable to connect to LBRY')); } }); } checkDaemonStarted(); }); } // Flow thinks this could be empty, but it will always reuturn a promise // $FlowFixMe return Lbry.connectPromise; } }; function checkAndParse(response) { if (response.status >= 200 && response.status < 300) { return response.json(); } return response.json().then(json => { let error; if (json.error) { const errorMessage = typeof json.error === 'object' ? json.error.message : json.error; error = new Error(errorMessage); } else { error = new Error('Protocol error with unknown response signature'); } return Promise.reject(error); }); } function apiCall(method, params, resolve, reject) { const counter = new Date().getTime(); const options = { method: 'POST', headers: Lbry.apiRequestHeaders, body: JSON.stringify({ jsonrpc: '2.0', method, params, id: counter }) }; return fetch(Lbry.daemonConnectionString, options).then(checkAndParse).then(response => { const error = response.error || response.result && response.result.error; if (error) { return reject(error); } return resolve(response.result); }).catch(reject); } function daemonCallWithResult(name, params = {}) { return new Promise((resolve, reject) => { apiCall(name, params, result => { resolve(result); }, reject); }); } // This is only for a fallback // If there is a Lbry method that is being called by an app, it should be added to /flow-typed/Lbry.js const lbryProxy = new Proxy(Lbry, { get(target, name) { if (name in target) { return target[name]; } return (params = {}) => new Promise((resolve, reject) => { apiCall(name, params, resolve, reject); }); } }); // const DEFAULT_SEARCH_RESULT_FROM = 0; const DEFAULT_SEARCH_SIZE = 20; function parseQueryParams(queryString) { if (queryString === '') return {}; const parts = queryString.split('?').pop().split('&').map(p => p.split('=')); const params = {}; parts.forEach(array => { const [first, second] = array; params[first] = second; }); return params; } function toQueryString(params) { if (!params) return ''; const parts = []; Object.keys(params).forEach(key => { if (Object.prototype.hasOwnProperty.call(params, key) && params[key]) { parts.push(`${key}=${params[key]}`); } }); return parts.join('&'); } const getSearchQueryString = (query, options = {}, includeUserOptions = false) => { const encodedQuery = encodeURIComponent(query); const queryParams = [`s=${encodedQuery}`, `size=${options.size || DEFAULT_SEARCH_SIZE}`, `from=${options.from || DEFAULT_SEARCH_RESULT_FROM}`]; if (includeUserOptions) { const claimType = options[SEARCH_OPTIONS.CLAIM_TYPE]; queryParams.push(`claimType=${claimType}`); // If they are only searching for channels, strip out the media info if (!claimType.includes(SEARCH_OPTIONS.INCLUDE_CHANNELS)) { queryParams.push(`mediaType=${[SEARCH_OPTIONS.MEDIA_FILE, SEARCH_OPTIONS.MEDIA_AUDIO, SEARCH_OPTIONS.MEDIA_VIDEO, SEARCH_OPTIONS.MEDIA_TEXT, SEARCH_OPTIONS.MEDIA_IMAGE, SEARCH_OPTIONS.MEDIA_APPLICATION].reduce((acc, currentOption) => options[currentOption] ? `${acc}${currentOption},` : acc, '')}`); } } return queryParams.join('&'); }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; const channelNameMinLength = 1; const claimIdMaxLength = 40; // see https://spec.lbry.com/#urls const regexInvalidURI = exports.regexInvalidURI = /[=&#:$@%?\u{0000}-\u{0008}\u{000b}-\u{000c}\u{000e}-\u{001F}\u{D800}-\u{DFFF}\u{FFFE}-\u{FFFF}]/gu; const regexAddress = /^(b|r)(?=[^0OIl]{32,33})[0-9A-Za-z]{32,33}$/; /** * Parses a LBRY name into its component parts. Throws errors with user-friendly * messages for invalid names. * * N.B. that "name" indicates the value in the name position of the URI. For * claims for channel content, this will actually be the channel name, and * the content name is in the path (e.g. lbry://@channel/content) * * In most situations, you'll want to use the contentName and channelName keys * and ignore the name key. * * Returns a dictionary with keys: * - name (string): The value in the "name" position in the URI. Note that this * could be either content name or channel name; see above. * - path (string, if persent) * - claimSequence (int, if present) * - bidPosition (int, if present) * - claimId (string, if present) * - isChannel (boolean) * - contentName (string): For anon claims, the name; for channel claims, the path * - channelName (string, if present): Channel name without @ */ function parseURI(URI, requireProto = false) { // Break into components. Empty sub-matches are converted to null const componentsRegex = new RegExp('^((?:lbry://)?)' + // protocol '([^:$#/]*)' + // claim name (stops at the first separator or end) '([:$#]?)([^/]*)' + // modifier separator, modifier (stops at the first path separator or end) '(/?)(.*)' // path separator, path ); const [proto, claimName, modSep, modVal, pathSep, path] = componentsRegex.exec(URI).slice(1).map(match => match || null); let contentName; // Validate protocol if (requireProto && !proto) { throw new Error(__('LBRY URIs must include a protocol prefix (lbry://).')); } // Validate and process name if (!claimName) { throw new Error(__('URI does not include name.')); } const isChannel = claimName.startsWith('@'); const channelName = isChannel ? claimName.slice(1) : claimName; if (isChannel) { if (!channelName) { throw new Error(__('No channel name after @.')); } if (channelName.length < channelNameMinLength) { throw new Error(__(`Channel names must be at least %s characters.`, channelNameMinLength)); } contentName = path; } const nameBadChars = (channelName || claimName).match(regexInvalidURI); if (nameBadChars) { throw new Error(__(`Invalid character %s in name: %s.`, nameBadChars.length === 1 ? '' : 's', nameBadChars.join(', '))); } // Validate and process modifier (claim ID, bid position or claim sequence) let claimId; let claimSequence; let bidPosition; if (modSep) { if (!modVal) { throw new Error(__(`No modifier provided after separator %s.`, modSep)); } if (modSep === '#') { claimId = modVal; } else if (modSep === ':') { claimSequence = modVal; } else if (modSep === '$') { bidPosition = modVal; } } if (claimId && (claimId.length > claimIdMaxLength || !claimId.match(/^[0-9a-f]+$/))) { throw new Error(__(`Invalid claim ID %s.`, claimId)); } if (claimSequence && !claimSequence.match(/^-?[1-9][0-9]*$/)) { throw new Error(__('Claim sequence must be a number.')); } if (bidPosition && !bidPosition.match(/^-?[1-9][0-9]*$/)) { throw new Error(__('Bid position must be a number.')); } // Validate and process path if (path) { if (!isChannel) { throw new Error(__('Only channel URIs may have a path.')); } const pathBadChars = path.match(regexInvalidURI); if (pathBadChars) { throw new Error(__(`Invalid character in path: %s`, pathBadChars.join(', '))); } contentName = path; } else if (pathSep) { throw new Error(__('No path provided after /')); } return _extends({ claimName, path, isChannel }, contentName ? { contentName } : {}, channelName ? { channelName } : {}, claimSequence ? { claimSequence: parseInt(claimSequence, 10) } : {}, bidPosition ? { bidPosition: parseInt(bidPosition, 10) } : {}, claimId ? { claimId } : {}, path ? { path } : {}); } /** * Takes an object in the same format returned by parse() and builds a URI. * * The channelName key will accept names with or without the @ prefix. */ function buildURI(URIObj, includeProto = true, protoDefault = 'lbry://') { const { claimId, claimSequence, bidPosition, contentName, channelName } = URIObj; let { claimName, path } = URIObj; if (channelName) { const channelNameFormatted = channelName.startsWith('@') ? channelName : `@${channelName}`; if (!claimName) { claimName = channelNameFormatted; } else if (claimName !== channelNameFormatted) { throw new Error(__('Received a channel content URI, but claim name and channelName do not match. "name" represents the value in the name position of the URI (lbry://name...), which for channel content will be the channel name. In most cases, to construct a channel URI you should just pass channelName and contentName.')); } } if (contentName) { if (!claimName) { claimName = contentName; } else if (!path) { path = contentName; } if (path && path !== contentName) { throw new Error(__('Path and contentName do not match. Only one is required; most likely you wanted contentName.')); } } return (includeProto ? protoDefault : '') + claimName + (claimId ? `#${claimId}` : '') + (claimSequence ? `:${claimSequence}` : '') + (bidPosition ? `${bidPosition}` : '') + (path ? `/${path}` : ''); } /* Takes a parseable LBRY URI and converts it to standard, canonical format */ function normalizeURI(URI) { const { claimName, path, bidPosition, claimSequence, claimId } = parseURI(URI); return buildURI({ claimName, path, claimSequence, bidPosition, claimId }); } function isURIValid(URI) { let parts; try { parts = parseURI(normalizeURI(URI)); } catch (error) { return false; } return parts && parts.claimName; } function isNameValid(claimName) { return !regexInvalidURI.test(claimName); } function isURIClaimable(URI) { let parts; try { parts = parseURI(normalizeURI(URI)); } catch (error) { return false; } return parts && parts.claimName && !parts.claimId && !parts.bidPosition && !parts.claimSequence && !parts.isChannel && !parts.path; } function convertToShareLink(URI) { const { claimName, path, bidPosition, claimSequence, claimId } = parseURI(URI); return buildURI({ claimName, path, claimSequence, bidPosition, claimId }, true, 'https://open.lbry.com/'); } var _extends$1 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; const selectState = state => state.search; const selectSearchValue = reselect.createSelector(selectState, state => state.searchQuery); const selectSearchOptions = reselect.createSelector(selectState, state => state.options); const selectSuggestions = reselect.createSelector(selectState, state => state.suggestions); const selectIsSearching = reselect.createSelector(selectState, state => state.searching); const selectSearchUrisByQuery = reselect.createSelector(selectState, state => state.urisByQuery); const makeSelectSearchUris = query => // replace statement below is kind of ugly, and repeated in doSearch action reselect.createSelector(selectSearchUrisByQuery, byQuery => byQuery[query ? query.replace(/^lbry:\/\//i, '').replace(/\//, ' ') : query]); const selectSearchBarFocused = reselect.createSelector(selectState, state => state.focused); const selectSearchSuggestions = reselect.createSelector(selectSearchValue, selectSuggestions, (query, suggestions) => { if (!query) { return []; } const queryIsPrefix = query === 'lbry:' || query === 'lbry:/' || query === 'lbry://' || query === 'lbry://@'; if (queryIsPrefix) { // If it is a prefix, wait until something else comes to figure out what to do return []; } else if (query.startsWith('lbry://')) { // If it starts with a prefix, don't show any autocomplete results // They are probably typing/pasting in a lbry uri return [{ value: query, type: query[7] === '@' ? SEARCH_TYPES.CHANNEL : SEARCH_TYPES.FILE }]; } let searchSuggestions = []; try { const uri = normalizeURI(query); const { claimName, isChannel } = parseURI(uri); searchSuggestions.push({ value: claimName, type: SEARCH_TYPES.SEARCH }, { value: uri, shorthand: isChannel ? claimName.slice(1) : claimName, type: isChannel ? SEARCH_TYPES.CHANNEL : SEARCH_TYPES.FILE }); } catch (e) { searchSuggestions.push({ value: query, type: SEARCH_TYPES.SEARCH }); } const apiSuggestions = suggestions[query] || []; if (apiSuggestions.length) { searchSuggestions = searchSuggestions.concat(apiSuggestions.filter(suggestion => suggestion !== query).map(suggestion => { // determine if it's a channel try { const uri = normalizeURI(suggestion); const { claimName, isChannel } = parseURI(uri); return { value: uri, shorthand: isChannel ? claimName.slice(1) : claimName, type: isChannel ? SEARCH_TYPES.CHANNEL : SEARCH_TYPES.FILE }; } catch (e) { // search result includes some character that isn't valid in claim names return { value: suggestion, type: SEARCH_TYPES.SEARCH }; } })); } return searchSuggestions; }); // Creates a query string based on the state in the search reducer // Can be overrided by passing in custom sizes/from values for other areas pagination const makeSelectQueryWithOptions = (customQuery, customSize, customFrom, isBackgroundSearch = false // If it's a background search, don't use the users settings ) => reselect.createSelector(selectSearchValue, selectSearchOptions, (query, options) => { const size = customSize || options[SEARCH_OPTIONS.RESULT_COUNT]; const queryString = getSearchQueryString(customQuery || query, _extends$1({}, options, { size, from: customFrom }), !isBackgroundSearch); return queryString; }); // function doToast(params) { if (!params) { throw Error("'params' object is required to create a toast notification"); } return { type: CREATE_TOAST, data: { id: uuid(), params } }; } function doDismissToast() { return { type: DISMISS_TOAST }; } function doError(error) { return { type: CREATE_ERROR, data: { error } }; } function doDismissError() { return { type: DISMISS_ERROR }; } var _extends$2 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; // const naughtyTags = ['porn', 'nsfw', 'mature', 'xxx'].reduce((acc, tag) => _extends$2({}, acc, { [tag]: true }), {}); const isClaimNsfw = claim => { if (!claim) { throw new Error('No claim passed to isClaimNsfw()'); } if (!claim.value) { return false; } const tags = claim.value.tags || []; for (let i = 0; i < tags.length; i += 1) { const tag = tags[i].toLowerCase(); if (naughtyTags[tag]) { return true; } } return false; }; // const selectState$1 = state => state.claims || {}; const selectClaimsById = reselect.createSelector(selectState$1, state => state.byId || {}); const selectCurrentChannelPage = reselect.createSelector(selectState$1, state => state.currentChannelPage || 1); const selectClaimsByUri = reselect.createSelector(selectState$1, selectClaimsById, (state, byId) => { const byUri = state.claimsByUri || {}; const claims = {}; Object.keys(byUri).forEach(uri => { const claimId = byUri[uri]; // NOTE returning a null claim allows us to differentiate between an // undefined (never fetched claim) and one which just doesn't exist. Not // the cleanest solution but couldn't think of anything better right now if (claimId === null) { claims[uri] = null; } else { claims[uri] = byId[claimId]; } }); return claims; }); const selectAllClaimsByChannel = reselect.createSelector(selectState$1, state => state.claimsByChannel || {}); const selectPendingById = reselect.createSelector(selectState$1, state => state.pendingById || {}); const selectPendingClaims = reselect.createSelector(selectState$1, state => Object.values(state.pendingById || [])); const makeSelectClaimIsPending = uri => reselect.createSelector(selectPendingById, pendingById => { const { claimId } = parseURI(uri); return Boolean(pendingById[claimId]); }); const makeSelectPendingByUri = uri => reselect.createSelector(selectPendingById, pendingById => { const { claimId } = parseURI(uri); return pendingById[claimId]; }); const makeSelectClaimForUri = uri => reselect.createSelector(selectClaimsByUri, selectPendingById, (byUri, pendingById) => { // Check if a claim is pending first // It won't be in claimsByUri because resolving it will return nothing const { claimId } = parseURI(uri); const pendingClaim = pendingById[claimId]; if (pendingClaim) { return pendingClaim; } return byUri && byUri[normalizeURI(uri)]; }); const selectMyClaimsRaw = reselect.createSelector(selectState$1, state => state.myClaims); const selectAbandoningIds = reselect.createSelector(selectState$1, state => Object.keys(state.abandoningById || {})); const selectMyActiveClaims = reselect.createSelector(selectMyClaimsRaw, selectAbandoningIds, (claims, abandoningIds) => new Set(claims && claims.map(claim => claim.claim_id).filter(claimId => Object.keys(abandoningIds).indexOf(claimId) === -1))); const makeSelectClaimIsMine = rawUri => { const uri = normalizeURI(rawUri); return reselect.createSelector(selectClaimsByUri, selectMyActiveClaims, (claims, myClaims) => claims && claims[uri] && claims[uri].claim_id && myClaims.has(claims[uri].claim_id)); }; const selectAllFetchingChannelClaims = reselect.createSelector(selectState$1, state => state.fetchingChannelClaims || {}); const makeSelectFetchingChannelClaims = uri => reselect.createSelector(selectAllFetchingChannelClaims, fetching => fetching && fetching[uri]); const makeSelectClaimsInChannelForPage = (uri, page) => reselect.createSelector(selectClaimsById, selectAllClaimsByChannel, (byId, allClaims) => { const byChannel = allClaims[uri] || {}; const claimIds = byChannel[page || 1]; if (!claimIds) return claimIds; return claimIds.map(claimId => byId[claimId]); }); const makeSelectClaimsInChannelForCurrentPageState = uri => reselect.createSelector(selectClaimsById, selectAllClaimsByChannel, selectCurrentChannelPage, (byId, allClaims, page) => { const byChannel = allClaims[uri] || {}; const claimIds = byChannel[page || 1]; if (!claimIds) return claimIds; return claimIds.map(claimId => byId[claimId]); }); const makeSelectMetadataForUri = uri => reselect.createSelector(makeSelectClaimForUri(uri), claim => { const metadata = claim && claim.value; return metadata || (claim === undefined ? undefined : null); }); const makeSelectMetadataItemForUri = (uri, key) => reselect.createSelector(makeSelectMetadataForUri(uri), metadata => { return metadata ? metadata[key] : undefined; }); const makeSelectTitleForUri = uri => reselect.createSelector(makeSelectMetadataForUri(uri), metadata => metadata && metadata.title); const makeSelectDateForUri = uri => reselect.createSelector(makeSelectClaimForUri(uri), claim => { const timestamp = claim && claim.value && (claim.value.release_time ? claim.value.release_time * 1000 : claim.meta.creation_timestamp * 1000); if (!timestamp) { return undefined; } const dateObj = new Date(timestamp); return dateObj; }); const makeSelectContentTypeForUri = uri => reselect.createSelector(makeSelectClaimForUri(uri), claim => { const source = claim && claim.value && claim.value.source; return source ? source.media_type : undefined; }); const makeSelectThumbnailForUri = uri => reselect.createSelector(makeSelectClaimForUri(uri), claim => { const thumbnail = claim && claim.value && claim.value.thumbnail; return thumbnail ? thumbnail.url : undefined; }); const makeSelectCoverForUri = uri => reselect.createSelector(makeSelectClaimForUri(uri), claim => { const cover = claim && claim.value && claim.value.cover; return cover ? cover.url : undefined; }); const selectIsFetchingClaimListMine = reselect.createSelector(selectState$1, state => state.isFetchingClaimListMine); const selectMyClaims = reselect.createSelector(selectMyActiveClaims, selectClaimsById, selectAbandoningIds, selectPendingClaims, (myClaimIds, byId, abandoningIds, pendingClaims) => { const claims = []; myClaimIds.forEach(id => { const claim = byId[id]; if (claim && abandoningIds.indexOf(id) === -1) claims.push(claim); }); return [...claims, ...pendingClaims]; }); const selectMyClaimsWithoutChannels = reselect.createSelector(selectMyClaims, myClaims => myClaims.filter(claim => !claim.name.match(/^@/))); const selectMyClaimUrisWithoutChannels = reselect.createSelector(selectMyClaimsWithoutChannels, myClaims => myClaims.map(claim => `lbry://${claim.name}#${claim.claim_id}`)); const selectAllMyClaimsByOutpoint = reselect.createSelector(selectMyClaimsRaw, claims => new Set(claims && claims.length ? claims.map(claim => `${claim.txid}:${claim.nout}`) : null)); const selectMyClaimsOutpoints = reselect.createSelector(selectMyClaims, myClaims => { const outpoints = []; myClaims.forEach(claim => outpoints.push(`${claim.txid}:${claim.nout}`)); return outpoints; }); const selectFetchingMyChannels = reselect.createSelector(selectState$1, state => state.fetchingMyChannels); const selectMyChannelClaims = reselect.createSelector(selectState$1, selectClaimsById, (state, byId) => { const ids = state.myChannelClaims || []; const claims = []; ids.forEach(id => { if (byId[id]) { // I'm not sure why this check is necessary, but it ought to be a quick fix for https://github.com/lbryio/lbry-desktop/issues/544 claims.push(byId[id]); } }); return claims; }); const selectResolvingUris = reselect.createSelector(selectState$1, state => state.resolvingUris || []); const makeSelectIsUriResolving = uri => reselect.createSelector(selectResolvingUris, resolvingUris => resolvingUris && resolvingUris.indexOf(uri) !== -1); const selectPlayingUri = reselect.createSelector(selectState$1, state => state.playingUri); const selectChannelClaimCounts = reselect.createSelector(selectState$1, state => state.channelClaimCounts || {}); const makeSelectTotalItemsForChannel = uri => reselect.createSelector(selectChannelClaimCounts, byUri => byUri && byUri[uri]); const makeSelectTotalPagesForChannel = (uri, pageSize = 10) => reselect.createSelector(selectChannelClaimCounts, byUri => byUri && byUri[uri] && Math.ceil(byUri[uri] / pageSize)); const makeSelectNsfwCountFromUris = uris => reselect.createSelector(selectClaimsByUri, claims => uris.reduce((acc, uri) => { const claim = claims[uri]; if (claim && isClaimNsfw(claim)) { return acc + 1; } return acc; }, 0)); const makeSelectNsfwCountForChannel = uri => reselect.createSelector(selectClaimsById, selectAllClaimsByChannel, selectCurrentChannelPage, (byId, allClaims, page) => { const byChannel = allClaims[uri] || {}; const claimIds = byChannel[page || 1]; if (!claimIds) return 0; return claimIds.reduce((acc, claimId) => { const claim = byId[claimId]; if (isClaimNsfw(claim)) { return acc + 1; } return acc; }, 0); }); const makeSelectClaimIsNsfw = uri => reselect.createSelector(makeSelectClaimForUri(uri), // Eventually these will come from some list of tags that are considered adult // Or possibly come from users settings of what tags they want to hide // For now, there is just a hard coded list of tags inside `isClaimNsfw` // selectNaughtyTags(), claim => { if (!claim) { return false; } return isClaimNsfw(claim); }); const makeSelectRecommendedContentForUri = uri => reselect.createSelector(makeSelectClaimForUri(uri), selectSearchUrisByQuery, (claim, searchUrisByQuery) => { const atVanityURI = !uri.includes('#'); let recommendedContent; if (claim) { // If we are at a vanity uri, build the full uri so we can properly filter const currentUri = atVanityURI ? buildURI({ claimId: claim.claim_id, claimName: claim.name }) : uri; const { title } = claim.value; const searchQuery = getSearchQueryString(title.replace(/\//, ' ')); let searchUris = searchUrisByQuery[searchQuery]; if (searchUris) { searchUris = searchUris.filter(searchUri => searchUri !== currentUri); recommendedContent = searchUris; } } return recommendedContent; }); const makeSelectFirstRecommendedFileForUri = uri => reselect.createSelector(makeSelectRecommendedContentForUri(uri), recommendedContent => recommendedContent ? recommendedContent[0] : null); // Returns the associated channel uri for a given claim uri // accepts a regular claim uri lbry://something // returns the channel uri that created this claim lbry://@channel const makeSelectChannelForClaimUri = (uri, includePrefix = false) => reselect.createSelector(makeSelectClaimForUri(uri), claim => { if (!claim || !claim.signing_channel) { return null; } const { claim_id: claimId, name } = claim.signing_channel; let channel = `${name}#${claimId}`; return includePrefix ? `lbry://${channel}` : channel; }); const makeSelectTagsForUri = uri => reselect.createSelector(makeSelectMetadataForUri(uri), metadata => { return metadata && metadata.tags || []; }); const selectFetchingClaimSearch = reselect.createSelector(selectState$1, state => state.fetchingClaimSearch); const selectLastClaimSearchUris = reselect.createSelector(selectState$1, state => state.lastClaimSearchUris); const selectState$2 = state => state.wallet || {}; const selectWalletState = selectState$2; const selectWalletIsEncrypted = reselect.createSelector(selectState$2, state => state.walletIsEncrypted); const selectWalletEncryptPending = reselect.createSelector(selectState$2, state => state.walletEncryptPending); const selectWalletEncryptSucceeded = reselect.createSelector(selectState$2, state => state.walletEncryptSucceded); const selectWalletEncryptResult = reselect.createSelector(selectState$2, state => state.walletEncryptResult); const selectWalletDecryptPending = reselect.createSelector(selectState$2, state => state.walletDecryptPending); const selectWalletDecryptSucceeded = reselect.createSelector(selectState$2, state => state.walletDecryptSucceded); const selectWalletDecryptResult = reselect.createSelector(selectState$2, state => state.walletDecryptResult); const selectWalletUnlockPending = reselect.createSelector(selectState$2, state => state.walletUnlockPending); const selectWalletUnlockSucceeded = reselect.createSelector(selectState$2, state => state.walletUnlockSucceded); const selectWalletUnlockResult = reselect.createSelector(selectState$2, state => state.walletUnlockResult); const selectWalletLockPending = reselect.createSelector(selectState$2, state => state.walletLockPending); const selectWalletLockSucceeded = reselect.createSelector(selectState$2, state => state.walletLockSucceded); const selectWalletLockResult = reselect.createSelector(selectState$2, state => state.walletLockResult); const selectBalance = reselect.createSelector(selectState$2, state => state.balance); const selectTotalBalance = reselect.createSelector(selectState$2, state => state.totalBalance); const selectTransactionsById = reselect.createSelector(selectState$2, state => state.transactions || {}); const selectSupportsByOutpoint = reselect.createSelector(selectState$2, state => state.supports || {}); const selectTransactionItems = reselect.createSelector(selectTransactionsById, byId => { const items = []; Object.keys(byId).forEach(txid => { const tx = byId[txid]; // ignore dust/fees // it is fee only txn if all infos are also empty if (Math.abs(tx.value) === Math.abs(tx.fee) && tx.claim_info.length === 0 && tx.support_info.length === 0 && tx.update_info.length === 0 && tx.abandon_info.length === 0) { return; } const append = []; append.push(...tx.claim_info.map(item => Object.assign({}, tx, item, { type: item.claim_name[0] === '@' ? CHANNEL : PUBLISH }))); append.push(...tx.support_info.map(item => Object.assign({}, tx, item, { type: !item.is_tip ? SUPPORT : TIP }))); append.push(...tx.update_info.map(item => Object.assign({}, tx, item, { type: UPDATE }))); append.push(...tx.abandon_info.map(item => Object.assign({}, tx, item, { type: ABANDON }))); if (!append.length) { append.push(Object.assign({}, tx, { type: tx.value < 0 ? SPEND : RECEIVE })); } items.push(...append.map(item => { // value on transaction, amount on outpoint // amount is always positive, but should match sign of value const balanceDelta = parseFloat(item.balance_delta); const value = parseFloat(item.value); const amount = balanceDelta || value; const fee = parseFloat(tx.fee); return { txid, timestamp: tx.timestamp, date: tx.timestamp ? new Date(Number(tx.timestamp) * 1000) : null, amount, fee, claim_id: item.claim_id, claim_name: item.claim_name, type: item.type || SPEND, nout: item.nout, confirmations: tx.confirmations }; })); }); return items.sort((tx1, tx2) => { if (!tx1.timestamp && !tx2.timestamp) { return 0; } else if (!tx1.timestamp && tx2.timestamp) { return -1; } else if (tx1.timestamp && !tx2.timestamp) { return 1; } return tx2.timestamp - tx1.timestamp; }); }); const selectRecentTransactions = reselect.createSelector(selectTransactionItems, transactions => { const threshold = new Date(); threshold.setDate(threshold.getDate() - 7); return transactions.filter(transaction => { if (!transaction.date) { return true; // pending transaction } return transaction.date > threshold; }); }); const selectHasTransactions = reselect.createSelector(selectTransactionItems, transactions => transactions && transactions.length > 0); const selectIsFetchingTransactions = reselect.createSelector(selectState$2, state => state.fetchingTransactions); const selectIsSendingSupport = reselect.createSelector(selectState$2, state => state.sendingSupport); const selectReceiveAddress = reselect.createSelector(selectState$2, state => state.receiveAddress); const selectGettingNewAddress = reselect.createSelector(selectState$2, state => state.gettingNewAddress); const selectDraftTransaction = reselect.createSelector(selectState$2, state => state.draftTransaction || {}); const selectDraftTransactionAmount = reselect.createSelector(selectDraftTransaction, draft => draft.amount); const selectDraftTransactionAddress = reselect.createSelector(selectDraftTransaction, draft => draft.address); const selectDraftTransactionError = reselect.createSelector(selectDraftTransaction, draft => draft.error); const selectBlocks = reselect.createSelector(selectState$2, state => state.blocks); const selectCurrentHeight = reselect.createSelector(selectState$2, state => state.latestBlock); const selectTransactionListFilter = reselect.createSelector(selectState$2, state => state.transactionListFilter || ''); function formatCredits(amount, precision) { if (Number.isNaN(parseFloat(amount))) return '0'; return parseFloat(amount).toFixed(precision || 1).replace(/\.?0+$/, ''); } function formatFullPrice(amount, precision = 1) { let formated = ''; const quantity = amount.toString().split('.'); const fraction = quantity[1]; if (fraction) { const decimals = fraction.split(''); const first = decimals.filter(number => number !== '0')[0]; const index = decimals.indexOf(first); // Set format fraction formated = `.${fraction.substring(0, index + precision)}`; } return parseFloat(quantity[0] + formated); } function creditsToString(amount) { const creditString = parseFloat(amount).toFixed(8); return creditString; } function doUpdateBalance() { return (dispatch, getState) => { const { wallet: { balance: balanceInStore } } = getState(); lbryProxy.account_balance().then(balanceAsString => { const balance = parseFloat(balanceAsString); if (balanceInStore !== balance) { dispatch({ type: UPDATE_BALANCE, data: { balance } }); } }); }; } function doUpdateTotalBalance() { return (dispatch, getState) => { const { wallet: { totalBalance: totalBalanceInStore } } = getState(); lbryProxy.account_list().then(accountList => { const { lbc_mainnet: accounts } = accountList; const totalSatoshis = accounts.length === 1 ? accounts[0].satoshis : accounts.reduce((a, b) => a.satoshis + b.satoshis); const totalBalance = (Number.isNaN(totalSatoshis) ? 0 : totalSatoshis) / Math.pow(10, 8); if (totalBalanceInStore !== totalBalance) { dispatch({ type: UPDATE_TOTAL_BALANCE, data: { totalBalance } }); } }); }; } function doBalanceSubscribe() { return dispatch => { dispatch(doUpdateBalance()); setInterval(() => dispatch(doUpdateBalance()), 5000); }; } function doTotalBalanceSubscribe() { return dispatch => { dispatch(doUpdateTotalBalance()); setInterval(() => dispatch(doUpdateTotalBalance()), 5000); }; } function doFetchTransactions() { return dispatch => { dispatch(doFetchSupports()); dispatch({ type: FETCH_TRANSACTIONS_STARTED }); lbryProxy.utxo_release().then(() => lbryProxy.transaction_list()).then(results => { dispatch({ type: FETCH_TRANSACTIONS_COMPLETED, data: { transactions: results } }); }); }; } function doFetchSupports() { return dispatch => { dispatch({ type: FETCH_SUPPORTS_STARTED }); lbryProxy.support_list().then(results => { dispatch({ type: FETCH_SUPPORTS_COMPLETED, data: { supports: results } }); }); }; } function doGetNewAddress() { return dispatch => { dispatch({ type: GET_NEW_ADDRESS_STARTED }); lbryProxy.address_unused().then(address => { dispatch({ type: GET_NEW_ADDRESS_COMPLETED, data: { address } }); }); }; } function doCheckAddressIsMine(address) { return dispatch => { dispatch({ type: CHECK_ADDRESS_IS_MINE_STARTED }); lbryProxy.address_is_mine({ address }).then(isMine => { if (!isMine) dispatch(doGetNewAddress()); dispatch({ type: CHECK_ADDRESS_IS_MINE_COMPLETED }); }); }; } function doSendDraftTransaction(address, amount) { return (dispatch, getState) => { const state = getState(); const balance = selectBalance(state); if (balance - amount <= 0) { dispatch(doToast({ title: 'Insufficient credits', message: 'Insufficient credits' })); return; } dispatch({ type: SEND_TRANSACTION_STARTED }); const successCallback = response => { if (response.txid) { dispatch({ type: SEND_TRANSACTION_COMPLETED }); dispatch(doToast({ message: `You sent ${amount} LBC`, linkText: 'History', linkTarget: '/wallet' })); } else { dispatch({ type: SEND_TRANSACTION_FAILED, data: { error: response } }); dispatch(doToast({ message: 'Transaction failed', isError: true })); } }; const errorCallback = error => { dispatch({ type: SEND_TRANSACTION_FAILED, data: { error: error.message } }); dispatch(doToast({ message: 'Transaction failed', isError: true })); }; lbryProxy.account_send({ addresses: [address], amount: creditsToString(amount) }).then(successCallback, errorCallback); }; } function doSetDraftTransactionAmount(amount) { return { type: SET_DRAFT_TRANSACTION_AMOUNT, data: { amount } }; } function doSetDraftTransactionAddress(address) { return { type: SET_DRAFT_TRANSACTION_ADDRESS, data: { address } }; } function doSendTip(amount, claimId, uri, successCallback, errorCallback) { return (dispatch, getState) => { const state = getState(); const balance = selectBalance(state); if (balance - amount <= 0) { dispatch(doToast({ message: 'Insufficient credits', isError: true })); return; } const success = () => { dispatch(doToast({ message: __(`You sent ${amount} LBC as a tip, Mahalo!`), linkText: __('History'), linkTarget: __('/wallet') })); dispatch({ type: SUPPORT_TRANSACTION_COMPLETED }); if (successCallback) { successCallback(); } }; const error = err => { dispatch(doToast({ message: __(`There was an error sending support funds.`), isError: true })); dispatch({ type: SUPPORT_TRANSACTION_FAILED, data: { error: err } }); if (errorCallback) { errorCallback(); } }; dispatch({ type: SUPPORT_TRANSACTION_STARTED }); lbryProxy.support_create({ claim_id: claimId, amount: creditsToString(amount), tip: true }).then(success, error); }; } function doWalletEncrypt(newPassword) { return dispatch => { dispatch({ type: WALLET_ENCRYPT_START }); lbryProxy.account_encrypt({ new_password: newPassword }).then(result => { if (result === true) { dispatch({ type: WALLET_ENCRYPT_COMPLETED, result }); } else { dispatch({ type: WALLET_ENCRYPT_FAILED, result }); } }); }; } function doWalletUnlock(password) { return dispatch => { dispatch({ type: WALLET_UNLOCK_START }); lbryProxy.account_unlock({ password }).then(result => { if (result === true) { dispatch({ type: WALLET_UNLOCK_COMPLETED, result }); } else { dispatch({ type: WALLET_UNLOCK_FAILED, result }); } }); }; } function doWalletDecrypt() { return dispatch => { dispatch({ type: WALLET_DECRYPT_START }); lbryProxy.account_decrypt().then(result => { if (result === true) { dispatch({ type: WALLET_DECRYPT_COMPLETED, result }); } else { dispatch({ type: WALLET_DECRYPT_FAILED, result }); } }); }; } function doWalletStatus() { return dispatch => { dispatch({ type: WALLET_STATUS_START }); lbryProxy.status().then(status => { if (status && status.wallet) { dispatch({ type: WALLET_STATUS_COMPLETED, result: status.wallet.is_encrypted }); } }); }; } function doSetTransactionListFilter(filterOption) { return { type: SET_TRANSACTION_LIST_FILTER, data: filterOption }; } function doUpdateBlockHeight() { return dispatch => lbryProxy.status().then(status => { if (status.wallet) { dispatch({ type: UPDATE_CURRENT_HEIGHT, data: status.wallet.blocks }); } }); } // https://github.com/reactjs/redux/issues/911 function batchActions(...actions) { return { type: 'BATCH_ACTIONS', actions }; } var _extends$3 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function doResolveUris(uris, returnCachedClaims = false) { return (dispatch, getState) => { const normalizedUris = uris.map(normalizeURI); const state = getState(); const resolvingUris = selectResolvingUris(state); const claimsByUri = selectClaimsByUri(state); const urisToResolve = normalizedUris.filter(uri => { if (resolvingUris.includes(uri)) { return false; } return returnCachedClaims ? !claimsByUri[uri] : true; }); if (urisToResolve.length === 0) { return; } dispatch({ type: RESOLVE_URIS_STARTED, data: { uris: normalizedUris } }); const resolveInfo = {}; lbryProxy.resolve({ urls: urisToResolve }).then(result => { Object.entries(result).forEach(([uri, uriResolveInfo]) => { const fallbackResolveInfo = { stream: null, claimsInChannel: null, channel: null }; // Flow has terrible Object.entries support // https://github.com/facebook/flow/issues/2221 if (uriResolveInfo) { if (uriResolveInfo.error) { resolveInfo[uri] = _extends$3({}, fallbackResolveInfo); } else { let result = {}; if (uriResolveInfo.value_type === 'channel') { result.channel = uriResolveInfo; // $FlowFixMe result.claimsInChannel = uriResolveInfo.meta.claims_in_channel; } else { result.stream = uriResolveInfo; if (uriResolveInfo.signing_channel) { result.channel = uriResolveInfo.signing_channel; <<<<<<< HEAD result.claimsInChannel = uriResolveInfo.signing_channel.meta && uriResolveInfo.signing_channel.meta.claims_in_channel || 0; ======= result.claimsInChannel = uriResolveInfo.meta && uriResolveInfo.meta.claims_in_channel || 0; >>>>>>> add tags } } // $FlowFixMe resolveInfo[uri] = result; } } }); dispatch({ type: RESOLVE_URIS_COMPLETED, data: { resolveInfo } }); }); }; } function doResolveUri(uri) { return doResolveUris([uri]); } function doFetchClaimListMine() { return dispatch => { dispatch({ type: FETCH_CLAIM_LIST_MINE_STARTED }); lbryProxy.claim_list().then(claims => { dispatch({ type: FETCH_CLAIM_LIST_MINE_COMPLETED, data: { claims } }); }); }; } function doAbandonClaim(txid, nout) { const outpoint = `${txid}:${nout}`; return (dispatch, getState) => { const state = getState(); const myClaims = selectMyClaimsRaw(state); const mySupports = selectSupportsByOutpoint(state); // A user could be trying to abandon a support or one of their claims const claimToAbandon = myClaims.find(claim => claim.txid === txid && claim.nout === nout); const supportToAbandon = mySupports[outpoint]; if (!claimToAbandon && !supportToAbandon) { console.error('No associated support or claim with txid: ', txid); return; } const data = claimToAbandon ? { claimId: claimToAbandon.claim_id } : { outpoint: `${supportToAbandon.txid}:${supportToAbandon.nout}` }; const isClaim = !!claimToAbandon; const startedActionType = isClaim ? ABANDON_CLAIM_STARTED : ABANDON_SUPPORT_STARTED; const completedActionType = isClaim ? ABANDON_CLAIM_STARTED : ABANDON_SUPPORT_COMPLETED; dispatch({ type: startedActionType, data }); const errorCallback = () => { dispatch(doToast({ message: isClaim ? 'Error abandoning your claim' : 'Error unlocking your tip', isError: true })); }; const successCallback = () => { dispatch({ type: completedActionType, data }); dispatch(doToast({ message: isClaim ? 'Successfully abandoned your claim' : 'Successfully unlocked your tip!' })); // After abandoning, call claim_list to show the claim as abandoned // Also fetch transactions to show the new abandon transaction dispatch(doFetchClaimListMine()); dispatch(doFetchTransactions()); }; const abandonParams = { txid, nout, blocking: true }; let method; if (supportToAbandon) { method = 'support_abandon'; } else if (claimToAbandon) { const { name: claimName } = claimToAbandon; method = claimName.startsWith('@') ? 'channel_abandon' : 'stream_abandon'; } if (!method) { console.error('No "method" chosen for claim or support abandon'); return; } lbryProxy[method](abandonParams).then(successCallback, errorCallback); }; } function doFetchClaimsByChannel(uri, page = 1) { return dispatch => { dispatch({ type: FETCH_CHANNEL_CLAIMS_STARTED, data: { uri, page } }); lbryProxy.claim_search({ channel: uri, <<<<<<< HEAD valid_channel_signatures: true, ======= is_controlling: true, >>>>>>> add tags page: page || 1, order_by: ['release_time'] }).then(result => { const { items: claimsInChannel, page: returnedPage } = result; dispatch({ type: FETCH_CHANNEL_CLAIMS_COMPLETED, data: { uri, claims: claimsInChannel || [], page: returnedPage || undefined } }); }); }; } function doCreateChannel(name, amount) { return dispatch => { dispatch({ type: CREATE_CHANNEL_STARTED }); return lbryProxy.channel_create({ name, bid: creditsToString(amount) }) // outputs[0] is the certificate // outputs[1] is the change from the tx, not in the app currently .then(result => { const channelClaim = result.outputs[0]; dispatch({ type: CREATE_CHANNEL_COMPLETED, data: { channelClaim } }); }).catch(error => { dispatch({ type: CREATE_CHANNEL_FAILED, data: error }); }); }; } function doFetchChannelListMine() { return dispatch => { dispatch({ type: FETCH_CHANNEL_LIST_STARTED }); const callback = channels => { dispatch({ type: FETCH_CHANNEL_LIST_COMPLETED, data: { claims: channels } }); }; lbryProxy.channel_list().then(callback); }; } function doClaimSearch(amount = 20, options = {}) { return dispatch => { dispatch({ type: CLAIM_SEARCH_STARTED }); const success = data => { const resolveInfo = {}; const uris = []; data.items.forEach(stream => { resolveInfo[stream.permanent_url] = { stream }; uris.push(stream.permanent_url); }); dispatch({ type: CLAIM_SEARCH_COMPLETED, data: { resolveInfo, uris } }); }; const failure = err => { dispatch({ type: CLAIM_SEARCH_FAILED, error: err }); }; lbryProxy.claim_search(_extends$3({ page_size: amount }, options)).then(success, failure); }; } const selectState$3 = state => state.fileInfo || {}; const selectFileInfosByOutpoint = reselect.createSelector(selectState$3, state => state.byOutpoint || {}); const selectIsFetchingFileList = reselect.createSelector(selectState$3, state => state.isFetchingFileList); const selectIsFetchingFileListDownloadedOrPublished = reselect.createSelector(selectIsFetchingFileList, selectIsFetchingClaimListMine, (isFetchingFileList, isFetchingClaimListMine) => isFetchingFileList || isFetchingClaimListMine); const makeSelectFileInfoForUri = uri => reselect.createSelector(selectClaimsByUri, selectFileInfosByOutpoint, (claims, byOutpoint) => { const claim = claims[uri]; const outpoint = claim ? `${claim.txid}:${claim.nout}` : undefined; return outpoint ? byOutpoint[outpoint] : undefined; }); const selectDownloadingByOutpoint = reselect.createSelector(selectState$3, state => state.downloadingByOutpoint || {}); const makeSelectDownloadingForUri = uri => reselect.createSelector(selectDownloadingByOutpoint, makeSelectFileInfoForUri(uri), (byOutpoint, fileInfo) => { if (!fileInfo) return false; return byOutpoint[fileInfo.outpoint]; }); const selectUrisLoading = reselect.createSelector(selectState$3, state => state.urisLoading || {}); const makeSelectLoadingForUri = uri => reselect.createSelector(selectUrisLoading, byUri => byUri && byUri[uri]); const selectFileInfosDownloaded = reselect.createSelector(selectFileInfosByOutpoint, selectMyClaims, (byOutpoint, myClaims) => Object.values(byOutpoint).filter(fileInfo => { const myClaimIds = myClaims.map(claim => claim.claim_id); return fileInfo && myClaimIds.indexOf(fileInfo.claim_id) === -1 && (fileInfo.completed || fileInfo.written_bytes); })); // export const selectFileInfoForUri = (state, props) => { // const claims = selectClaimsByUri(state), // claim = claims[props.uri], // fileInfos = selectAllFileInfos(state), // outpoint = claim ? `${claim.txid}:${claim.nout}` : undefined; // return outpoint && fileInfos ? fileInfos[outpoint] : undefined; // }; const selectDownloadingFileInfos = reselect.createSelector(selectDownloadingByOutpoint, selectFileInfosByOutpoint, (downloadingByOutpoint, fileInfosByOutpoint) => { const outpoints = Object.keys(downloadingByOutpoint); const fileInfos = []; outpoints.forEach(outpoint => { const fileInfo = fileInfosByOutpoint[outpoint]; if (fileInfo) fileInfos.push(fileInfo); }); return fileInfos; }); const selectTotalDownloadProgress = reselect.createSelector(selectDownloadingFileInfos, fileInfos => { const progress = []; fileInfos.forEach(fileInfo => { progress.push(fileInfo.written_bytes / fileInfo.total_bytes * 100); }); const totalProgress = progress.reduce((a, b) => a + b, 0); if (fileInfos.length > 0) return totalProgress / fileInfos.length / 100.0; return -1; }); const selectSearchDownloadUris = query => reselect.createSelector(selectFileInfosDownloaded, selectClaimsById, (fileInfos, claimsById) => { if (!query || !fileInfos.length) { return null; } const queryParts = query.toLowerCase().split(' '); const searchQueryDictionary = {}; queryParts.forEach(subQuery => { searchQueryDictionary[subQuery] = subQuery; }); const arrayContainsQueryPart = array => { for (let i = 0; i < array.length; i += 1) { const subQuery = array[i]; if (searchQueryDictionary[subQuery]) { return true; } } return false; }; const downloadResultsFromQuery = []; fileInfos.forEach(fileInfo => { const { channel_name: channelName, claim_name: claimName, metadata } = fileInfo; const { author, description, title } = metadata; if (channelName) { const lowerCaseChannel = channelName.toLowerCase(); const strippedOutChannelName = lowerCaseChannel.slice(1); // trim off the @ if (searchQueryDictionary[channelName] || searchQueryDictionary[strippedOutChannelName]) { downloadResultsFromQuery.push(fileInfo); return; } } const nameParts = claimName.toLowerCase().split('-'); if (arrayContainsQueryPart(nameParts)) { downloadResultsFromQuery.push(fileInfo); return; } if (title) { const titleParts = title.toLowerCase().split(' '); if (arrayContainsQueryPart(titleParts)) { downloadResultsFromQuery.push(fileInfo); return; } } if (author) { const authorParts = author.toLowerCase().split(' '); if (arrayContainsQueryPart(authorParts)) { downloadResultsFromQuery.push(fileInfo); return; } } if (description) { const descriptionParts = description.toLowerCase().split(' '); if (arrayContainsQueryPart(descriptionParts)) { downloadResultsFromQuery.push(fileInfo); } } }); return downloadResultsFromQuery.length ? downloadResultsFromQuery.map(fileInfo => { const { channel_name: channelName, claim_id: claimId, claim_name: claimName } = fileInfo; const uriParams = {}; if (channelName) { const claim = claimsById[claimId]; if (claim && claim.signing_channel) { uriParams.claimId = claim.signing_channel.claim_id; } else { uriParams.claimId = claimId; } uriParams.channelName = channelName; uriParams.contentName = claimName; } else { uriParams.claimId = claimId; uriParams.claimName = claimName; } const uri = buildURI(uriParams); return uri; }) : null; }); const selectFileListPublishedSort = reselect.createSelector(selectState$3, state => state.fileListPublishedSort); const selectFileListDownloadedSort = reselect.createSelector(selectState$3, state => state.fileListDownloadedSort); const selectDownloadedUris = reselect.createSelector(selectFileInfosDownloaded, // We should use permament_url but it doesn't exist in file_list info => info.map(claim => `lbry://${claim.claim_name}#${claim.claim_id}`)); // const selectState$4 = state => state.file || {}; const selectPurchaseUriErrorMessage = reselect.createSelector(selectState$4, state => state.purchaseUriErrorMessage); const selectFailedPurchaseUris = reselect.createSelector(selectState$4, state => state.failedPurchaseUris); const selectPurchasedUris = reselect.createSelector(selectState$4, state => state.purchasedUris); const selectPurchasedStreamingUrls = reselect.createSelector(selectState$4, state => state.purchasedStreamingUrls); const selectLastPurchasedUri = reselect.createSelector(selectState$4, state => state.purchasedUris.length > 0 ? state.purchasedUris[state.purchasedUris.length - 1] : null); const makeSelectStreamingUrlForUri = uri => reselect.createSelector(selectPurchasedStreamingUrls, streamingUrls => streamingUrls && streamingUrls[uri]); // function doFileGet(uri, saveFile = true) { return dispatch => { dispatch({ type: LOADING_FILE_STARTED, data: { uri } }); // set save_file argument to True to save the file (old behaviour) lbryProxy.get({ uri, save_file: saveFile }).then(streamInfo => { const timeout = streamInfo === null || typeof streamInfo !== 'object'; if (timeout) { dispatch({ type: LOADING_FILE_FAILED, data: { uri } }); dispatch({ type: PURCHASE_URI_FAILED, data: { uri } }); dispatch(doToast({ message: `File timeout for uri ${uri}`, isError: true })); } else { // purchase was completed successfully const { streaming_url: streamingUrl } = streamInfo; dispatch({ type: PURCHASE_URI_COMPLETED, data: { uri, streamingUrl: !saveFile && streamingUrl ? streamingUrl : null } }); } }).catch(() => { dispatch({ type: LOADING_FILE_FAILED, data: { uri } }); dispatch({ type: PURCHASE_URI_FAILED, data: { uri } }); dispatch(doToast({ message: `Failed to download ${uri}, please try again. If this problem persists, visit https://lbry.com/faq/support for support.`, isError: true })); }); }; } function doPurchaseUri(uri, costInfo, saveFile = true) { return (dispatch, getState) => { dispatch({ type: PURCHASE_URI_STARTED, data: { uri } }); const state = getState(); const balance = selectBalance(state); const fileInfo = makeSelectFileInfoForUri(uri)(state); const downloadingByOutpoint = selectDownloadingByOutpoint(state); const alreadyDownloading = fileInfo && !!downloadingByOutpoint[fileInfo.outpoint]; const alreadyStreaming = makeSelectStreamingUrlForUri(uri)(state); if (alreadyDownloading || alreadyStreaming) { dispatch({ type: PURCHASE_URI_FAILED, data: { uri, error: `Already fetching uri: ${uri}` } }); return; } const { cost } = costInfo; if (parseFloat(cost) > balance) { dispatch({ type: PURCHASE_URI_FAILED, data: { uri, error: 'Insufficient credits' } }); return; } dispatch(doFileGet(uri, saveFile)); }; } function doDeletePurchasedUri(uri) { return { type: DELETE_PURCHASED_URI, data: { uri } }; } function doFetchFileInfo(uri) { return (dispatch, getState) => { const state = getState(); const claim = selectClaimsByUri(state)[uri]; const outpoint = claim ? `${claim.txid}:${claim.nout}` : null; const alreadyFetching = !!selectUrisLoading(state)[uri]; if (!alreadyFetching) { dispatch({ type: FETCH_FILE_INFO_STARTED, data: { outpoint } }); lbryProxy.file_list({ outpoint, full_status: true }).then(fileInfos => { dispatch({ type: FETCH_FILE_INFO_COMPLETED, data: { outpoint, fileInfo: fileInfos && fileInfos.length ? fileInfos[0] : null } }); }); } }; } function doFileList() { return (dispatch, getState) => { const state = getState(); const isFetching = selectIsFetchingFileList(state); if (!isFetching) { dispatch({ type: FILE_LIST_STARTED }); lbryProxy.file_list().then(fileInfos => { dispatch({ type: FILE_LIST_SUCCEEDED, data: { fileInfos } }); }); } }; } function doFetchFileInfosAndPublishedClaims() { return (dispatch, getState) => { const state = getState(); const isFetchingClaimListMine = selectIsFetchingClaimListMine(state); const isFetchingFileInfo = selectIsFetchingFileList(state); if (!isFetchingClaimListMine) dispatch(doFetchClaimListMine()); if (!isFetchingFileInfo) dispatch(doFileList()); }; } function doSetFileListSort(page, value) { return { type: SET_FILE_LIST_SORT, data: { page, value } }; } // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. function debouce(func, wait, immediate) { let timeout; return function () { const context = this; const args = arguments; const later = () => { timeout = null; if (!immediate) func.apply(context, args); }; const callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; } // function handleFetchResponse(response) { return response.status === 200 ? Promise.resolve(response.json()) : Promise.reject(new Error(response.statusText)); } // const DEBOUNCED_SEARCH_SUGGESTION_MS = 300; // We can't use env's because they aren't passed into node_modules let CONNECTION_STRING = 'https://lighthouse.lbry.com/'; const setSearchApi = endpoint => { CONNECTION_STRING = endpoint.replace(/\/*$/, '/'); // exactly one slash at the end; }; const getSearchSuggestions = value => (dispatch, getState) => { const query = value.trim(); // strip out any basic stuff for more accurate search results let searchValue = query.replace(/lbry:\/\//g, '').replace(/-/g, ' '); if (searchValue.includes('#')) { // This should probably be more robust, but I think it's fine for now // Remove everything after # to get rid of the claim id searchValue = searchValue.substring(0, searchValue.indexOf('#')); } const suggestions = selectSuggestions(getState()); if (suggestions[searchValue]) { return; } fetch(`${CONNECTION_STRING}autocomplete?s=${searchValue}`).then(handleFetchResponse).then(apiSuggestions => { dispatch({ type: UPDATE_SEARCH_SUGGESTIONS, data: { query: searchValue, suggestions: apiSuggestions } }); }).catch(() => { // If the fetch fails, do nothing // Basic search suggestions are already populated at this point }); }; const throttledSearchSuggestions = debouce((dispatch, query) => { dispatch(getSearchSuggestions(query)); }, DEBOUNCED_SEARCH_SUGGESTION_MS); const doUpdateSearchQuery = (query, shouldSkipSuggestions) => dispatch => { dispatch({ type: UPDATE_SEARCH_QUERY, data: { query } }); // Don't fetch new suggestions if the user just added a space if (!query.endsWith(' ') || !shouldSkipSuggestions) { throttledSearchSuggestions(dispatch, query); } }; const doSearch = (rawQuery, // pass in a query if you don't want to search for what's in the search bar size, // only pass in if you don't want to use the users setting (ex: related content) from, isBackgroundSearch = false) => (dispatch, getState) => { const query = rawQuery.replace(/^lbry:\/\//i, '').replace(/\//, ' '); if (!query) { dispatch({ type: SEARCH_FAIL }); return; } const state = getState(); const queryWithOptions = makeSelectQueryWithOptions(query, size, from, isBackgroundSearch)(state); // If we have already searched for something, we don't need to do anything const urisForQuery = makeSelectSearchUris(queryWithOptions)(state); if (urisForQuery && !!urisForQuery.length) { return; } dispatch({ type: SEARCH_START }); // If the user is on the file page with a pre-populated uri and they select // the search option without typing anything, searchQuery will be empty // We need to populate it so the input is filled on the search page // isBackgroundSearch means the search is happening in the background, don't update the search query if (!state.search.searchQuery && !isBackgroundSearch) { dispatch(doUpdateSearchQuery(query)); } fetch(`${CONNECTION_STRING}search?${queryWithOptions}`).then(handleFetchResponse).then(data => { const uris = []; const actions = []; data.forEach(result => { const uri = buildURI({ claimName: result.name, claimId: result.claimId }); actions.push(doResolveUri(uri)); uris.push(uri); }); actions.push({ type: SEARCH_SUCCESS, data: { query: queryWithOptions, uris } }); dispatch(batchActions(...actions)); }).catch(() => { dispatch({ type: SEARCH_FAIL }); }); }; const doFocusSearchInput = () => dispatch => dispatch({ type: SEARCH_FOCUS }); const doBlurSearchInput = () => dispatch => dispatch({ type: SEARCH_BLUR }); const doUpdateSearchOptions = newOptions => (dispatch, getState) => { const state = getState(); const searchValue = selectSearchValue(state); dispatch({ type: UPDATE_SEARCH_OPTIONS, data: newOptions }); if (searchValue) { // After updating, perform a search with the new options dispatch(doSearch(searchValue)); } }; function savePosition(claimId, outpoint, position) { return dispatch => { dispatch({ type: SET_CONTENT_POSITION, data: { claimId, outpoint, position } }); }; } // const doToggleTagFollow = name => ({ type: TOGGLE_TAG_FOLLOW, data: { name } }); const doAddTag = name => ({ type: TAG_ADD, data: { name } }); const doDeleteTag = name => ({ type: TAG_DELETE, data: { name } }); var _extends$4 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; const reducers = {}; const defaultState = { byId: {}, claimsByUri: {}, claimsByChannel: {}, channelClaimCounts: {}, fetchingChannelClaims: {}, resolvingUris: [], // This should not be a Set // Storing sets in reducers can cause issues myChannelClaims: new Set(), fetchingMyChannels: false, abandoningById: {}, pendingById: {}, fetchingClaimSearch: false, lastClaimSearchUris: [] }; function handleClaimAction(state, action) { const { resolveInfo } = action.data; const byUri = Object.assign({}, state.claimsByUri); const byId = Object.assign({}, state.byId); const channelClaimCounts = Object.assign({}, state.channelClaimCounts); Object.entries(resolveInfo).forEach(([uri, resolveResponse]) => { // $FlowFixMe if (resolveResponse.claimsInChannel) { // $FlowFixMe channelClaimCounts[uri] = resolveResponse.claimsInChannel; } }); // $FlowFixMe Object.entries(resolveInfo).forEach(([uri, { channel, stream }]) => { if (stream) { byId[stream.claim_id] = stream; byUri[uri] = stream.claim_id; } if (channel) { byId[channel.claim_id] = channel; byUri[stream ? channel.permanent_url : uri] = channel.claim_id; } if (!stream && !channel) { byUri[uri] = null; } }); return Object.assign({}, state, { byId, claimsByUri: byUri, channelClaimCounts, resolvingUris: (state.resolvingUris || []).filter(uri => !resolveInfo[uri]) }); } reducers[RESOLVE_URIS_COMPLETED] = (state, action) => { return _extends$4({}, handleClaimAction(state, action)); }; reducers[FETCH_CLAIM_LIST_MINE_STARTED] = state => Object.assign({}, state, { isFetchingClaimListMine: true }); reducers[FETCH_CLAIM_LIST_MINE_COMPLETED] = (state, action) => { const { claims } = action.data; const byId = Object.assign({}, state.byId); const byUri = Object.assign({}, state.claimsByUri); const pendingById = Object.assign({}, state.pendingById); claims.forEach(claim => { const uri = buildURI({ claimName: claim.name, claimId: claim.claim_id }); if (claim.type && claim.type.match(/claim|update/)) { if (claim.confirmations < 1) { pendingById[claim.claim_id] = claim; delete byId[claim.claim_id]; delete byUri[claim.claim_id]; } else { byId[claim.claim_id] = claim; byUri[uri] = claim.claim_id; } } }); // Remove old pending publishes Object.values(pendingById) // $FlowFixMe .filter(pendingClaim => byId[pendingClaim.claim_id]).forEach(pendingClaim => { // $FlowFixMe delete pendingById[pendingClaim.claim_id]; }); return Object.assign({}, state, { isFetchingClaimListMine: false, myClaims: claims, byId, claimsByUri: byUri, pendingById }); }; reducers[FETCH_CHANNEL_LIST_STARTED] = state => Object.assign({}, state, { fetchingMyChannels: true }); reducers[FETCH_CHANNEL_LIST_COMPLETED] = (state, action) => { const { claims } = action.data; const myChannelClaims = new Set(state.myChannelClaims); const byId = Object.assign({}, state.byId); claims.forEach(claim => { myChannelClaims.add(claim.claim_id); byId[claim.claim_id] = claim; }); return Object.assign({}, state, { byId, fetchingMyChannels: false, myChannelClaims }); }; reducers[FETCH_CHANNEL_CLAIMS_STARTED] = (state, action) => { const { uri, page } = action.data; const fetchingChannelClaims = Object.assign({}, state.fetchingChannelClaims); fetchingChannelClaims[uri] = page; return Object.assign({}, state, { fetchingChannelClaims, currentChannelPage: page }); }; reducers[FETCH_CHANNEL_CLAIMS_COMPLETED] = (state, action) => { const { uri, claims, page } = action.data; const claimsByChannel = Object.assign({}, state.claimsByChannel); const byChannel = Object.assign({}, claimsByChannel[uri]); const allClaimIds = new Set(byChannel.all); const currentPageClaimIds = []; const byId = Object.assign({}, state.byId); const fetchingChannelClaims = Object.assign({}, state.fetchingChannelClaims); const claimsByUri = Object.assign({}, state.claimsByUri); if (claims !== undefined) { claims.forEach(claim => { allClaimIds.add(claim.claim_id); currentPageClaimIds.push(claim.claim_id); byId[claim.claim_id] = claim; claimsByUri[`lbry://${claim.name}#${claim.claim_id}`] = claim.claim_id; }); } byChannel.all = allClaimIds; byChannel[page] = currentPageClaimIds; claimsByChannel[uri] = byChannel; delete fetchingChannelClaims[uri]; return Object.assign({}, state, { claimsByChannel, byId, fetchingChannelClaims, claimsByUri, currentChannelPage: page }); }; reducers[ABANDON_CLAIM_STARTED] = (state, action) => { const { claimId } = action.data; const abandoningById = Object.assign({}, state.abandoningById); abandoningById[claimId] = true; return Object.assign({}, state, { abandoningById }); }; reducers[ABANDON_CLAIM_SUCCEEDED] = (state, action) => { const { claimId } = action.data; const byId = Object.assign({}, state.byId); const claimsByUri = Object.assign({}, state.claimsByUri); Object.keys(claimsByUri).forEach(uri => { if (claimsByUri[uri] === claimId) { delete claimsByUri[uri]; } }); delete byId[claimId]; return Object.assign({}, state, { byId, claimsByUri }); }; reducers[CREATE_CHANNEL_COMPLETED] = (state, action) => { const channelClaim = action.data.channelClaim; const byId = Object.assign({}, state.byId); const myChannelClaims = new Set(state.myChannelClaims); byId[channelClaim.claim_id] = channelClaim; myChannelClaims.add(channelClaim.claim_id); return Object.assign({}, state, { byId, myChannelClaims }); }; reducers[RESOLVE_URIS_STARTED] = (state, action) => { const { uris } = action.data; const oldResolving = state.resolvingUris || []; const newResolving = oldResolving.slice(); uris.forEach(uri => { if (!newResolving.includes(uri)) { newResolving.push(uri); } }); return Object.assign({}, state, { resolvingUris: newResolving }); }; reducers[CLAIM_SEARCH_STARTED] = state => { return Object.assign({}, state, { fetchingClaimSearch: true }); }; reducers[CLAIM_SEARCH_COMPLETED] = (state, action) => { return _extends$4({}, handleClaimAction(state, action), { fetchingClaimSearch: false, lastClaimSearchUris: action.data.uris }); }; reducers[CLAIM_SEARCH_FAILED] = state => { return Object.assign({}, state, { fetchingClaimSearch: false }); }; function claimsReducer(state = defaultState, action) { const handler = reducers[action.type]; if (handler) return handler(state, action); return state; } var _extends$5 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; const reducers$1 = {}; const defaultState$1 = { failedPurchaseUris: [], purchasedUris: [], purchasedStreamingUrls: {}, purchaseUriErrorMessage: '' }; reducers$1[PURCHASE_URI_STARTED] = (state, action) => { const { uri } = action.data; const newFailedPurchaseUris = state.failedPurchaseUris.slice(); if (newFailedPurchaseUris.includes(uri)) { newFailedPurchaseUris.splice(newFailedPurchaseUris.indexOf(uri), 1); } return _extends$5({}, state, { failedPurchaseUris: newFailedPurchaseUris, purchaseUriErrorMessage: '' }); }; reducers$1[PURCHASE_URI_COMPLETED] = (state, action) => { const { uri, streamingUrl } = action.data; const newPurchasedUris = state.purchasedUris.slice(); const newFailedPurchaseUris = state.failedPurchaseUris.slice(); const newPurchasedStreamingUrls = Object.assign({}, state.purchasedStreamingUrls); if (!newPurchasedUris.includes(uri)) { newPurchasedUris.push(uri); } if (newFailedPurchaseUris.includes(uri)) { newFailedPurchaseUris.splice(newFailedPurchaseUris.indexOf(uri), 1); } if (streamingUrl) { newPurchasedStreamingUrls[uri] = streamingUrl; } return _extends$5({}, state, { failedPurchaseUris: newFailedPurchaseUris, purchasedUris: newPurchasedUris, purchasedStreamingUrls: newPurchasedStreamingUrls, purchaseUriErrorMessage: '' }); }; reducers$1[PURCHASE_URI_FAILED] = (state, action) => { const { uri, error } = action.data; const newFailedPurchaseUris = state.failedPurchaseUris.slice(); if (!newFailedPurchaseUris.includes(uri)) { newFailedPurchaseUris.push(uri); } return _extends$5({}, state, { failedPurchaseUris: newFailedPurchaseUris, purchaseUriErrorMessage: error }); }; reducers$1[DELETE_PURCHASED_URI] = (state, action) => { const { uri } = action.data; const newPurchasedUris = state.purchasedUris.slice(); if (newPurchasedUris.includes(uri)) { newPurchasedUris.splice(newPurchasedUris.indexOf(uri), 1); } return _extends$5({}, state, { purchasedUris: newPurchasedUris }); }; function fileReducer(state = defaultState$1, action) { const handler = reducers$1[action.type]; if (handler) return handler(state, action); return state; } var _extends$6 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; const reducers$2 = {}; const defaultState$2 = { fileListPublishedSort: DATE_NEW, fileListDownloadedSort: DATE_NEW }; reducers$2[FILE_LIST_STARTED] = state => Object.assign({}, state, { isFetchingFileList: true }); reducers$2[FILE_LIST_SUCCEEDED] = (state, action) => { const { fileInfos } = action.data; const newByOutpoint = Object.assign({}, state.byOutpoint); const pendingByOutpoint = Object.assign({}, state.pendingByOutpoint); fileInfos.forEach(fileInfo => { const { outpoint } = fileInfo; if (outpoint) newByOutpoint[fileInfo.outpoint] = fileInfo; }); return Object.assign({}, state, { isFetchingFileList: false, byOutpoint: newByOutpoint, pendingByOutpoint }); }; reducers$2[FETCH_FILE_INFO_STARTED] = (state, action) => { const { outpoint } = action.data; const newFetching = Object.assign({}, state.fetching); newFetching[outpoint] = true; return Object.assign({}, state, { fetching: newFetching }); }; reducers$2[FETCH_FILE_INFO_COMPLETED] = (state, action) => { const { fileInfo, outpoint } = action.data; const newByOutpoint = Object.assign({}, state.byOutpoint); const newFetching = Object.assign({}, state.fetching); newByOutpoint[outpoint] = fileInfo; delete newFetching[outpoint]; return Object.assign({}, state, { byOutpoint: newByOutpoint, fetching: newFetching }); }; reducers$2[DOWNLOADING_STARTED] = (state, action) => { const { uri, outpoint, fileInfo } = action.data; const newByOutpoint = Object.assign({}, state.byOutpoint); const newDownloading = Object.assign({}, state.downloadingByOutpoint); const newLoading = Object.assign({}, state.urisLoading); newDownloading[outpoint] = true; newByOutpoint[outpoint] = fileInfo; delete newLoading[uri]; return Object.assign({}, state, { downloadingByOutpoint: newDownloading, urisLoading: newLoading, byOutpoint: newByOutpoint }); }; reducers$2[DOWNLOADING_PROGRESSED] = (state, action) => { const { outpoint, fileInfo } = action.data; const newByOutpoint = Object.assign({}, state.byOutpoint); const newDownloading = Object.assign({}, state.downloadingByOutpoint); newByOutpoint[outpoint] = fileInfo; newDownloading[outpoint] = true; return Object.assign({}, state, { byOutpoint: newByOutpoint, downloadingByOutpoint: newDownloading }); }; reducers$2[DOWNLOADING_CANCELED] = (state, action) => { const { outpoint } = action.data; const newDownloading = Object.assign({}, state.downloadingByOutpoint); delete newDownloading[outpoint]; return Object.assign({}, state, { downloadingByOutpoint: newDownloading }); }; reducers$2[DOWNLOADING_COMPLETED] = (state, action) => { const { outpoint, fileInfo } = action.data; const newByOutpoint = Object.assign({}, state.byOutpoint); const newDownloading = Object.assign({}, state.downloadingByOutpoint); newByOutpoint[outpoint] = fileInfo; delete newDownloading[outpoint]; return Object.assign({}, state, { byOutpoint: newByOutpoint, downloadingByOutpoint: newDownloading }); }; reducers$2[FILE_DELETE] = (state, action) => { const { outpoint } = action.data; const newByOutpoint = Object.assign({}, state.byOutpoint); const downloadingByOutpoint = Object.assign({}, state.downloadingByOutpoint); delete newByOutpoint[outpoint]; delete downloadingByOutpoint[outpoint]; return Object.assign({}, state, { byOutpoint: newByOutpoint, downloadingByOutpoint }); }; reducers$2[LOADING_VIDEO_STARTED] = (state, action) => { const { uri } = action.data; const newLoading = Object.assign({}, state.urisLoading); newLoading[uri] = true; const newErrors = _extends$6({}, state.errors); if (uri in newErrors) delete newErrors[uri]; return Object.assign({}, state, { urisLoading: newLoading, errors: _extends$6({}, newErrors) }); }; reducers$2[LOADING_VIDEO_FAILED] = (state, action) => { const { uri } = action.data; const newLoading = Object.assign({}, state.urisLoading); delete newLoading[uri]; const newErrors = _extends$6({}, state.errors); newErrors[uri] = true; return Object.assign({}, state, { urisLoading: newLoading, errors: _extends$6({}, newErrors) }); }; reducers$2[SET_FILE_LIST_SORT] = (state, action) => { const pageSortStates = { [PUBLISHED]: 'fileListPublishedSort', [DOWNLOADED]: 'fileListDownloadedSort' }; const pageSortState = pageSortStates[action.data.page]; const { value } = action.data; return Object.assign({}, state, { [pageSortState]: value }); }; function fileInfoReducer(state = defaultState$2, action) { const handler = reducers$2[action.type]; if (handler) return handler(state, action); return state; } // util for creating reducers // based off of redux-actions // https://redux-actions.js.org/docs/api/handleAction.html#handleactions // eslint-disable-next-line import/prefer-default-export const handleActions = (actionMap, defaultState) => (state = defaultState, action) => { const handler = actionMap[action.type]; if (handler) { const newState = handler(state, action); return Object.assign({}, state, newState); } // just return the original state if no handler // returning a copy here breaks redux-persist return state; }; var _extends$7 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; const defaultState$3 = { notifications: [], toasts: [], errors: [] }; const notificationsReducer = handleActions({ // Toasts [CREATE_TOAST]: (state, action) => { const toast = action.data; const newToasts = state.toasts.slice(); newToasts.push(toast); return _extends$7({}, state, { toasts: newToasts }); }, [DISMISS_TOAST]: state => { const newToasts = state.toasts.slice(); newToasts.shift(); return _extends$7({}, state, { toasts: newToasts }); }, // Notifications [CREATE_NOTIFICATION]: (state, action) => { const notification = action.data; const newNotifications = state.notifications.slice(); newNotifications.push(notification); return _extends$7({}, state, { notifications: newNotifications }); }, // Used to mark notifications as read/dismissed [EDIT_NOTIFICATION]: (state, action) => { const { notification } = action.data; let notifications = state.notifications.slice(); notifications = notifications.map(pastNotification => pastNotification.id === notification.id ? notification : pastNotification); return _extends$7({}, state, { notifications }); }, [DELETE_NOTIFICATION]: (state, action) => { const { id } = action.data; let newNotifications = state.notifications.slice(); newNotifications = newNotifications.filter(notification => notification.id !== id); return _extends$7({}, state, { notifications: newNotifications }); }, // Errors [CREATE_ERROR]: (state, action) => { const error = action.data; const newErrors = state.errors.slice(); newErrors.push(error); return _extends$7({}, state, { errors: newErrors }); }, [DISMISS_ERROR]: state => { const newErrors = state.errors.slice(); newErrors.shift(); return _extends$7({}, state, { errors: newErrors }); } }, defaultState$3); var _extends$8 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; const defaultState$4 = { isActive: false, // does the user have any typed text in the search input focused: false, // is the search input focused searchQuery: '', // needs to be an empty string for input focusing options: { [SEARCH_OPTIONS.RESULT_COUNT]: 30, [SEARCH_OPTIONS.CLAIM_TYPE]: SEARCH_OPTIONS.INCLUDE_FILES_AND_CHANNELS, [SEARCH_OPTIONS.MEDIA_AUDIO]: true, [SEARCH_OPTIONS.MEDIA_VIDEO]: true, [SEARCH_OPTIONS.MEDIA_TEXT]: true, [SEARCH_OPTIONS.MEDIA_IMAGE]: true, [SEARCH_OPTIONS.MEDIA_APPLICATION]: true }, suggestions: {}, urisByQuery: {} }; const searchReducer = handleActions({ [SEARCH_START]: state => _extends$8({}, state, { searching: true }), [SEARCH_SUCCESS]: (state, action) => { const { query, uris } = action.data; return _extends$8({}, state, { searching: false, urisByQuery: Object.assign({}, state.urisByQuery, { [query]: uris }) }); }, [SEARCH_FAIL]: state => _extends$8({}, state, { searching: false }), [UPDATE_SEARCH_QUERY]: (state, action) => _extends$8({}, state, { searchQuery: action.data.query, isActive: true }), [UPDATE_SEARCH_SUGGESTIONS]: (state, action) => _extends$8({}, state, { suggestions: _extends$8({}, state.suggestions, { [action.data.query]: action.data.suggestions }) }), // sets isActive to false so the uri will be populated correctly if the // user is on a file page. The search query will still be present on any // other page [DISMISS_NOTIFICATION]: state => _extends$8({}, state, { isActive: false }), [SEARCH_FOCUS]: state => _extends$8({}, state, { focused: true }), [SEARCH_BLUR]: state => _extends$8({}, state, { focused: false }), [UPDATE_SEARCH_OPTIONS]: (state, action) => { const { options: oldOptions } = state; const newOptions = action.data; const options = _extends$8({}, oldOptions, newOptions); return _extends$8({}, state, { options }); } }, defaultState$4); var _extends$9 = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; const buildDraftTransaction = () => ({ amount: undefined, address: undefined }); // TODO: Split into common success and failure types // See details in https://github.com/lbryio/lbry/issues/1307 const defaultState$5 = { balance: undefined, totalBalance: undefined, latestBlock: undefined, transactions: {}, fetchingTransactions: false, supports: {}, fetchingSupports: false, abandoningSupportsByOutpoint: {}, gettingNewAddress: false, draftTransaction: buildDraftTransaction(), sendingSupport: false, walletIsEncrypted: false, walletEncryptPending: false, walletEncryptSucceded: null, walletEncryptResult: null, walletDecryptPending: false, walletDecryptSucceded: null, walletDecryptResult: null, walletUnlockPending: false, walletUnlockSucceded: null, walletUnlockResult: null, walletLockPending: false, walletLockSucceded: null, walletLockResult: null, transactionListFilter: 'all' }; const walletReducer = handleActions({ [FETCH_TRANSACTIONS_STARTED]: state => _extends$9({}, state, { fetchingTransactions: true }), [FETCH_TRANSACTIONS_COMPLETED]: (state, action) => { const byId = _extends$9({}, state.transactions); const { transactions } = action.data; transactions.forEach(transaction => { byId[transaction.txid] = transaction; }); return _extends$9({}, state, { transactions: byId, fetchingTransactions: false }); }, [FETCH_SUPPORTS_STARTED]: state => _extends$9({}, state, { fetchingSupports: true }), [FETCH_SUPPORTS_COMPLETED]: (state, action) => { const byOutpoint = state.supports; const { supports } = action.data; supports.forEach(transaction => { const { txid, nout } = transaction; byOutpoint[`${txid}:${nout}`] = transaction; }); return _extends$9({}, state, { supports: byOutpoint, fetchingSupports: false }); }, [ABANDON_SUPPORT_STARTED]: (state, action) => { const { outpoint } = action.data; const currentlyAbandoning = state.abandoningSupportsByOutpoint; currentlyAbandoning[outpoint] = true; return _extends$9({}, state, { abandoningSupportsByOutpoint: currentlyAbandoning }); }, [ABANDON_SUPPORT_COMPLETED]: (state, action) => { const { outpoint } = action.data; const byOutpoint = state.supports; const currentlyAbandoning = state.abandoningSupportsByOutpoint; delete currentlyAbandoning[outpoint]; delete byOutpoint[outpoint]; return _extends$9({}, state, { supports: byOutpoint, abandoningSupportsById: currentlyAbandoning }); }, [GET_NEW_ADDRESS_STARTED]: state => _extends$9({}, state, { gettingNewAddress: true }), [GET_NEW_ADDRESS_COMPLETED]: (state, action) => { const { address } = action.data; return _extends$9({}, state, { gettingNewAddress: false, receiveAddress: address }); }, [UPDATE_BALANCE]: (state, action) => _extends$9({}, state, { balance: action.data.balance }), [UPDATE_TOTAL_BALANCE]: (state, action) => _extends$9({}, state, { totalBalance: action.data.totalBalance }), [CHECK_ADDRESS_IS_MINE_STARTED]: state => _extends$9({}, state, { checkingAddressOwnership: true }), [CHECK_ADDRESS_IS_MINE_COMPLETED]: state => _extends$9({}, state, { checkingAddressOwnership: false }), [SET_DRAFT_TRANSACTION_AMOUNT]: (state, action) => { const oldDraft = state.draftTransaction; const newDraft = _extends$9({}, oldDraft, { amount: parseFloat(action.data.amount) }); return _extends$9({}, state, { draftTransaction: newDraft }); }, [SET_DRAFT_TRANSACTION_ADDRESS]: (state, action) => { const oldDraft = state.draftTransaction; const newDraft = _extends$9({}, oldDraft, { address: action.data.address }); return _extends$9({}, state, { draftTransaction: newDraft }); }, [SEND_TRANSACTION_STARTED]: state => { const newDraftTransaction = _extends$9({}, state.draftTransaction, { sending: true }); return _extends$9({}, state, { draftTransaction: newDraftTransaction }); }, [SEND_TRANSACTION_COMPLETED]: state => Object.assign({}, state, { draftTransaction: buildDraftTransaction() }), [SEND_TRANSACTION_FAILED]: (state, action) => { const newDraftTransaction = Object.assign({}, state.draftTransaction, { sending: false, error: action.data.error }); return _extends$9({}, state, { draftTransaction: newDraftTransaction }); }, [SUPPORT_TRANSACTION_STARTED]: state => _extends$9({}, state, { sendingSupport: true }), [SUPPORT_TRANSACTION_COMPLETED]: state => _extends$9({}, state, { sendingSupport: false }), [SUPPORT_TRANSACTION_FAILED]: (state, action) => _extends$9({}, state, { error: action.data.error, sendingSupport: false }), [WALLET_STATUS_COMPLETED]: (state, action) => _extends$9({}, state, { walletIsEncrypted: action.result }), [WALLET_ENCRYPT_START]: state => _extends$9({}, state, { walletEncryptPending: true, walletEncryptSucceded: null, walletEncryptResult: null }), [WALLET_ENCRYPT_COMPLETED]: (state, action) => _extends$9({}, state, { walletEncryptPending: false, walletEncryptSucceded: true, walletEncryptResult: action.result }), [WALLET_ENCRYPT_FAILED]: (state, action) => _extends$9({}, state, { walletEncryptPending: false, walletEncryptSucceded: false, walletEncryptResult: action.result }), [WALLET_DECRYPT_START]: state => _extends$9({}, state, { walletDecryptPending: true, walletDecryptSucceded: null, walletDecryptResult: null }), [WALLET_DECRYPT_COMPLETED]: (state, action) => _extends$9({}, state, { walletDecryptPending: false, walletDecryptSucceded: true, walletDecryptResult: action.result }), [WALLET_DECRYPT_FAILED]: (state, action) => _extends$9({}, state, { walletDecryptPending: false, walletDecryptSucceded: false, walletDecryptResult: action.result }), [WALLET_UNLOCK_START]: state => _extends$9({}, state, { walletUnlockPending: true, walletUnlockSucceded: null, walletUnlockResult: null }), [WALLET_UNLOCK_COMPLETED]: (state, action) => _extends$9({}, state, { walletUnlockPending: false, walletUnlockSucceded: true, walletUnlockResult: action.result }), [WALLET_UNLOCK_FAILED]: (state, action) => _extends$9({}, state, { walletUnlockPending: false, walletUnlockSucceded: false, walletUnlockResult: action.result }), [WALLET_LOCK_START]: state => _extends$9({}, state, { walletLockPending: false, walletLockSucceded: null, walletLockResult: null }), [WALLET_LOCK_COMPLETED]: (state, action) => _extends$9({}, state, { walletLockPending: false, walletLockSucceded: true, walletLockResult: action.result }), [WALLET_LOCK_FAILED]: (state, action) => _extends$9({}, state, { walletLockPending: false, walletLockSucceded: false, walletLockResult: action.result }), [SET_TRANSACTION_LIST_FILTER]: (state, action) => _extends$9({}, state, { transactionListFilter: action.data }), [UPDATE_CURRENT_HEIGHT]: (state, action) => _extends$9({}, state, { latestBlock: action.data }) }, defaultState$5); var _extends$a = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; const reducers$3 = {}; const defaultState$6 = { positions: {} }; reducers$3[SET_CONTENT_POSITION] = (state, action) => { const { claimId, outpoint, position } = action.data; return _extends$a({}, state, { positions: _extends$a({}, state.positions, { [claimId]: _extends$a({}, state.positions[claimId], { [outpoint]: position }) }) }); }; function contentReducer(state = defaultState$6, action) { const handler = reducers$3[action.type]; if (handler) return handler(state, action); return state; } var _extends$b = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; const tagsReducerBuilder = defaultState => handleActions({ [TOGGLE_TAG_FOLLOW]: (state, action) => { const { followedTags } = state; const { name } = action.data; let newFollowedTags = followedTags.slice(); if (newFollowedTags.includes(name)) { newFollowedTags = newFollowedTags.filter(tag => tag !== name); } else { newFollowedTags.push(name); } return _extends$b({}, state, { followedTags: newFollowedTags }); }, [TAG_ADD]: (state, action) => { const { knownTags } = state; const { name } = action.data; let newKnownTags = _extends$b({}, knownTags); newKnownTags[name] = { name }; return _extends$b({}, state, { knownTags: newKnownTags }); }, [TAG_DELETE]: (state, action) => { const { knownTags, followedTags } = state; const { name } = action.data; let newKnownTags = _extends$b({}, knownTags); delete newKnownTags[name]; const newFollowedTags = followedTags.filter(tag => tag !== name); return _extends$b({}, state, { knownTags: newKnownTags, followedTags: newFollowedTags }); } }, defaultState); const selectState$5 = state => state.content || {}; const makeSelectContentPositionForUri = uri => reselect.createSelector(selectState$5, makeSelectClaimForUri(uri), (state, claim) => { if (!claim) { return null; } const outpoint = `${claim.txid}:${claim.nout}`; const id = claim.claim_id; return state.positions[id] ? state.positions[id][outpoint] : null; }); var _extends$c = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; const selectState$6 = state => state.notifications || {}; const selectToast = reselect.createSelector(selectState$6, state => { if (state.toasts.length) { const { id, params } = state.toasts[0]; return _extends$c({ id }, params); } return null; }); const selectError = reselect.createSelector(selectState$6, state => { if (state.errors.length) { const { error } = state.errors[0]; return { error }; } return null; }); // const selectState$7 = state => state.tags || {}; const selectKnownTagsByName = reselect.createSelector(selectState$7, state => state.knownTags); const selectFollowedTagsList = reselect.createSelector(selectState$7, state => state.followedTags); const selectFollowedTags = reselect.createSelector(selectFollowedTagsList, followedTags => followedTags.map(tag => ({ name: tag })).sort((a, b) => a.name.localeCompare(b.name))); const selectUnfollowedTags = reselect.createSelector(selectKnownTagsByName, selectFollowedTagsList, (tagsByName, followedTags) => { const followedTagsSet = new Set(followedTags); let tagsToReturn = []; Object.keys(tagsByName).forEach(key => { if (!followedTagsSet.has(key)) { const { name } = tagsByName[key]; tagsToReturn.push({ name }); } }); return tagsToReturn; }); exports.ACTIONS = action_types; exports.Lbry = lbryProxy; exports.PAGES = pages; exports.SEARCH_OPTIONS = SEARCH_OPTIONS; exports.SEARCH_TYPES = SEARCH_TYPES; exports.SETTINGS = settings; exports.SORT_OPTIONS = sort_options; exports.THUMBNAIL_STATUSES = thumbnail_upload_statuses; exports.TRANSACTIONS = transaction_types; exports.batchActions = batchActions; exports.buildURI = buildURI; exports.claimsReducer = claimsReducer; exports.contentReducer = contentReducer; exports.convertToShareLink = convertToShareLink; exports.creditsToString = creditsToString; exports.doAbandonClaim = doAbandonClaim; exports.doAddTag = doAddTag; exports.doBalanceSubscribe = doBalanceSubscribe; exports.doBlurSearchInput = doBlurSearchInput; exports.doCheckAddressIsMine = doCheckAddressIsMine; exports.doClaimSearch = doClaimSearch; exports.doCreateChannel = doCreateChannel; exports.doDeletePurchasedUri = doDeletePurchasedUri; exports.doDeleteTag = doDeleteTag; exports.doDismissError = doDismissError; exports.doDismissToast = doDismissToast; exports.doError = doError; exports.doFetchChannelListMine = doFetchChannelListMine; exports.doFetchClaimListMine = doFetchClaimListMine; exports.doFetchClaimsByChannel = doFetchClaimsByChannel; exports.doFetchFileInfo = doFetchFileInfo; exports.doFetchFileInfosAndPublishedClaims = doFetchFileInfosAndPublishedClaims; exports.doFetchTransactions = doFetchTransactions; exports.doFileGet = doFileGet; exports.doFileList = doFileList; exports.doFocusSearchInput = doFocusSearchInput; exports.doGetNewAddress = doGetNewAddress; exports.doPurchaseUri = doPurchaseUri; exports.doResolveUri = doResolveUri; exports.doResolveUris = doResolveUris; exports.doSearch = doSearch; exports.doSendDraftTransaction = doSendDraftTransaction; exports.doSendTip = doSendTip; exports.doSetDraftTransactionAddress = doSetDraftTransactionAddress; exports.doSetDraftTransactionAmount = doSetDraftTransactionAmount; exports.doSetFileListSort = doSetFileListSort; exports.doSetTransactionListFilter = doSetTransactionListFilter; exports.doToast = doToast; exports.doToggleTagFollow = doToggleTagFollow; exports.doTotalBalanceSubscribe = doTotalBalanceSubscribe; exports.doUpdateBalance = doUpdateBalance; exports.doUpdateBlockHeight = doUpdateBlockHeight; exports.doUpdateSearchOptions = doUpdateSearchOptions; exports.doUpdateSearchQuery = doUpdateSearchQuery; exports.doUpdateTotalBalance = doUpdateTotalBalance; exports.doWalletDecrypt = doWalletDecrypt; exports.doWalletEncrypt = doWalletEncrypt; exports.doWalletStatus = doWalletStatus; exports.doWalletUnlock = doWalletUnlock; exports.fileInfoReducer = fileInfoReducer; exports.fileReducer = fileReducer; exports.formatCredits = formatCredits; exports.formatFullPrice = formatFullPrice; exports.isClaimNsfw = isClaimNsfw; exports.isNameValid = isNameValid; exports.isURIClaimable = isURIClaimable; exports.isURIValid = isURIValid; exports.makeSelectChannelForClaimUri = makeSelectChannelForClaimUri; exports.makeSelectClaimForUri = makeSelectClaimForUri; exports.makeSelectClaimIsMine = makeSelectClaimIsMine; exports.makeSelectClaimIsNsfw = makeSelectClaimIsNsfw; exports.makeSelectClaimIsPending = makeSelectClaimIsPending; exports.makeSelectClaimsInChannelForCurrentPageState = makeSelectClaimsInChannelForCurrentPageState; exports.makeSelectClaimsInChannelForPage = makeSelectClaimsInChannelForPage; exports.makeSelectContentPositionForUri = makeSelectContentPositionForUri; exports.makeSelectContentTypeForUri = makeSelectContentTypeForUri; exports.makeSelectCoverForUri = makeSelectCoverForUri; exports.makeSelectDateForUri = makeSelectDateForUri; exports.makeSelectDownloadingForUri = makeSelectDownloadingForUri; exports.makeSelectFetchingChannelClaims = makeSelectFetchingChannelClaims; exports.makeSelectFileInfoForUri = makeSelectFileInfoForUri; exports.makeSelectFirstRecommendedFileForUri = makeSelectFirstRecommendedFileForUri; exports.makeSelectIsUriResolving = makeSelectIsUriResolving; exports.makeSelectLoadingForUri = makeSelectLoadingForUri; exports.makeSelectMetadataForUri = makeSelectMetadataForUri; exports.makeSelectMetadataItemForUri = makeSelectMetadataItemForUri; exports.makeSelectNsfwCountForChannel = makeSelectNsfwCountForChannel; exports.makeSelectNsfwCountFromUris = makeSelectNsfwCountFromUris; exports.makeSelectPendingByUri = makeSelectPendingByUri; exports.makeSelectQueryWithOptions = makeSelectQueryWithOptions; exports.makeSelectRecommendedContentForUri = makeSelectRecommendedContentForUri; exports.makeSelectSearchUris = makeSelectSearchUris; exports.makeSelectStreamingUrlForUri = makeSelectStreamingUrlForUri; exports.makeSelectTagsForUri = makeSelectTagsForUri; exports.makeSelectThumbnailForUri = makeSelectThumbnailForUri; exports.makeSelectTitleForUri = makeSelectTitleForUri; exports.makeSelectTotalItemsForChannel = makeSelectTotalItemsForChannel; exports.makeSelectTotalPagesForChannel = makeSelectTotalPagesForChannel; exports.normalizeURI = normalizeURI; exports.notificationsReducer = notificationsReducer; exports.parseQueryParams = parseQueryParams; exports.parseURI = parseURI; exports.regexAddress = regexAddress; exports.regexInvalidURI = regexInvalidURI; exports.savePosition = savePosition; exports.searchReducer = searchReducer; exports.selectAbandoningIds = selectAbandoningIds; exports.selectAllClaimsByChannel = selectAllClaimsByChannel; exports.selectAllFetchingChannelClaims = selectAllFetchingChannelClaims; exports.selectAllMyClaimsByOutpoint = selectAllMyClaimsByOutpoint; exports.selectBalance = selectBalance; exports.selectBlocks = selectBlocks; exports.selectChannelClaimCounts = selectChannelClaimCounts; exports.selectClaimsById = selectClaimsById; exports.selectClaimsByUri = selectClaimsByUri; exports.selectCurrentChannelPage = selectCurrentChannelPage; exports.selectDownloadedUris = selectDownloadedUris; exports.selectDownloadingByOutpoint = selectDownloadingByOutpoint; exports.selectDownloadingFileInfos = selectDownloadingFileInfos; exports.selectDraftTransaction = selectDraftTransaction; exports.selectDraftTransactionAddress = selectDraftTransactionAddress; exports.selectDraftTransactionAmount = selectDraftTransactionAmount; exports.selectDraftTransactionError = selectDraftTransactionError; exports.selectError = selectError; exports.selectFailedPurchaseUris = selectFailedPurchaseUris; exports.selectFetchingClaimSearch = selectFetchingClaimSearch; exports.selectFetchingMyChannels = selectFetchingMyChannels; exports.selectFileInfosByOutpoint = selectFileInfosByOutpoint; exports.selectFileInfosDownloaded = selectFileInfosDownloaded; exports.selectFileListDownloadedSort = selectFileListDownloadedSort; exports.selectFileListPublishedSort = selectFileListPublishedSort; exports.selectFollowedTags = selectFollowedTags; exports.selectGettingNewAddress = selectGettingNewAddress; exports.selectHasTransactions = selectHasTransactions; exports.selectIsFetchingClaimListMine = selectIsFetchingClaimListMine; exports.selectIsFetchingFileList = selectIsFetchingFileList; exports.selectIsFetchingFileListDownloadedOrPublished = selectIsFetchingFileListDownloadedOrPublished; exports.selectIsFetchingTransactions = selectIsFetchingTransactions; exports.selectIsSearching = selectIsSearching; exports.selectIsSendingSupport = selectIsSendingSupport; exports.selectLastClaimSearchUris = selectLastClaimSearchUris; exports.selectLastPurchasedUri = selectLastPurchasedUri; exports.selectMyActiveClaims = selectMyActiveClaims; exports.selectMyChannelClaims = selectMyChannelClaims; exports.selectMyClaimUrisWithoutChannels = selectMyClaimUrisWithoutChannels; exports.selectMyClaims = selectMyClaims; exports.selectMyClaimsOutpoints = selectMyClaimsOutpoints; exports.selectMyClaimsRaw = selectMyClaimsRaw; exports.selectMyClaimsWithoutChannels = selectMyClaimsWithoutChannels; exports.selectPendingById = selectPendingById; exports.selectPendingClaims = selectPendingClaims; exports.selectPlayingUri = selectPlayingUri; exports.selectPurchaseUriErrorMessage = selectPurchaseUriErrorMessage; exports.selectPurchasedStreamingUrls = selectPurchasedStreamingUrls; exports.selectPurchasedUris = selectPurchasedUris; exports.selectReceiveAddress = selectReceiveAddress; exports.selectRecentTransactions = selectRecentTransactions; exports.selectResolvingUris = selectResolvingUris; exports.selectSearchBarFocused = selectSearchBarFocused; exports.selectSearchDownloadUris = selectSearchDownloadUris; exports.selectSearchOptions = selectSearchOptions; exports.selectSearchState = selectState; exports.selectSearchSuggestions = selectSearchSuggestions; exports.selectSearchUrisByQuery = selectSearchUrisByQuery; exports.selectSearchValue = selectSearchValue; exports.selectSupportsByOutpoint = selectSupportsByOutpoint; exports.selectToast = selectToast; exports.selectTotalBalance = selectTotalBalance; exports.selectTotalDownloadProgress = selectTotalDownloadProgress; exports.selectTransactionItems = selectTransactionItems; exports.selectTransactionListFilter = selectTransactionListFilter; exports.selectTransactionsById = selectTransactionsById; exports.selectUnfollowedTags = selectUnfollowedTags; exports.selectUrisLoading = selectUrisLoading; exports.selectWalletDecryptPending = selectWalletDecryptPending; exports.selectWalletDecryptResult = selectWalletDecryptResult; exports.selectWalletDecryptSucceeded = selectWalletDecryptSucceeded; exports.selectWalletEncryptPending = selectWalletEncryptPending; exports.selectWalletEncryptResult = selectWalletEncryptResult; exports.selectWalletEncryptSucceeded = selectWalletEncryptSucceeded; exports.selectWalletIsEncrypted = selectWalletIsEncrypted; exports.selectWalletState = selectWalletState; exports.selectWalletUnlockPending = selectWalletUnlockPending; exports.selectWalletUnlockResult = selectWalletUnlockResult; exports.selectWalletUnlockSucceeded = selectWalletUnlockSucceeded; exports.setSearchApi = setSearchApi; exports.tagsReducerBuilder = tagsReducerBuilder; exports.toQueryString = toQueryString; exports.walletReducer = walletReducer;
import React from 'react'; import {Link} from 'react-router-dom'; export const HeroBanner = () => { return ( <div> <h2>Hero Banner</h2> <p>Some banner text</p> <Link to="videos">Videos</Link> </div> ); }; export default HeroBanner;
import { PLAYER_X, TURN, PLAYER_O } from '../helpers/actionTypes' const initialState = { p1: 'X', p2: 'O', turn: 'p1' } export function playerReducer(state = initialState, action) { switch (action.type) { case PLAYER_X: const newXState = { ...state } if (action.player === 'p1') { newXState.p1 = 'X' newXState.p2 = 'O' } else { newXState.p1 = 'O' newXState.p2 = 'X' } return newXState case PLAYER_O: const newOState = { ...state } if (action.player === 'p1') { newOState.p1 = 'O' newOState.p2 = 'X' } else { newOState.p1 = 'X' newOState.p2 = 'O' } return newOState case TURN: const newState = { ...state } if (newState.turn === 'p1') { newState.turn = 'p2' } else { newState.turn = 'p1' } return newState default: return state } }
let common = { socket: null }; ((g) => { g.globalfreespace = g.globalfreespace || {}; g.f = async (f) => { return f(); } g.addEventListener('load', () => { //common.socket = io.connect(); //common.socket.on('io_key', function(data) { //if (data && data.metric && data.weight && (data.metric.length === data.weight.length)) { //} //}); ///{“metric”:[1,2,3], weight:[1,1,2]} //実験として描画 //data1での実験 (async () => { let x = g.data1.timestamps; //await draw1("chart2",["日時",x],["騒音[dB]",g.data1["騒音[dB]"]],["温度[℃]",g.data1["温度[℃]"]]); await draw1("chart2",["日時",x],["エリア4の温度[℃]",g.data1["温度[℃]"]],["エリア6の温度[℃]",g.data2["温度[℃]"]]); //await draw1(x, g.data1["温度[℃]"], "日時", "温度[℃]", "chart2"); })(); //実験として描画 //data3での実験 (async () => { let d = [0, 0, 0, 0, 0, 0, 0, 0, 0], dd = g.data3; await g.f(() => { for (let i = 0; i < d.length; i++) { d[i] = dd["エリア" + (i + 1)] } }); await draw2(d, "人") })(); //実験として描画 //data1,data2での実験 /*(async () => { let d = [ [], [], [], g.data1["温度[℃]"], [], g.data2["温度[℃]"], [], [], [] ] await draw2(d, "℃") })();*/ }); //時系列グラフの領域に描画 //ただし,argsは[[index,数字の配列],[],...] const draw1 = async (id, ...args) => { let data = []; await g.f(() => { for (let i = 0, tmp = []; i < args[0][1].length; i++, tmp = []) { tmp.push(args[0][1][i]); for(let j = 1; j < args.length; j++){ tmp.push(args[j][1][i] | 0); } data.push(tmp); } }); let index = [] for(let i = 0; i < args.length; i++){ index.push(args[i][0]) } data.unshift(index) //折れ線グラフ let dataset = []; var timeparser = d3.timeFormat("%Y-%m-%e-%H-%M"); console.log(data); for(let i=1;i<data.length;i++){ dataset[i-1] = [(data[i][0]),(data[i][1])]; } /*dataset = dataset.map(function(d){ return {timeparser(d[0]),d[1]}; });*/ console.log(dataset); var w = 800; var h = 300; var width = 400; var height = 300; const padding=30; const xScale = d3.scaleLinear() .domain([0,d3.max(dataset,function(d){return d[0];})]) .range([padding,w-padding]); const yScale = d3.scaleLinear() .domain([0,d3.max(dataset,function(d){return d[1];})]) .range([h-padding,padding]); const xAxis = d3.axisBottom() .scale(xScale) .ticks(5); const yAxis = d3.axisLeft() .scale(yScale) .ticks(5); var svg = d3.select("body") .append("svg") .attr("width", w) .attr("height", h); svg.append("g") .attr("class","axis") .attr("transform","translate(0,"+(h-padding)+")") .call(xAxis); svg.append("g") .attr("class","axis") .attr("transform","translate("+padding+",0)") .call(yAxis); svg.append("path") .datum(dataset) .attr("fill","none") .attr("stroke","steelblue") .attr("stroke-width",1.5) .attr("d",d3.line() .x(function(d){return xScale(d[0]);}) .y(function(d){return yScale(d[1]);}) ); /* g.globalfreespace = data; google.charts.load('current', { packages: ['corechart'] }); google.charts.setOnLoadCallback(() => { let options = { isStacked: true }; g.chart2_options = options; let data = google.visualization.arrayToDataTable(g.globalfreespace); g.chart2_data = data; let stage = document.getElementById(id); let chart = new google.visualization.LineChart(stage); g.chart2 = chart; chart.draw(data, options); }); */ } const re_draw1 = async (id, ...args) => { let data = []; await g.f(() => { for (let i = 0, tmp = []; i < args[0][1].length; i++, tmp = []) { tmp.push(args[0][1][i]); for(let j = 1; j < args.length; j++){ tmp.push(args[j][1][i] | 0); } data.push(tmp); } }); let index = [] for(let i = 0; i < args.length; i++){ index.push(args[i][0]) } data.unshift(index) g.chart2.draw(google.visualization.arrayToDataTable(data), g.chart2_options); } //mapへの平均値の描画 //引数は9個のエリア「num」の含まれるary. [a1,a2,a3,a4,a5,a6,a7,a8,a9] それぞれの平均値を出力.ないときは”noData” //同じ数字は同じ色.var color = "hsl(" + hue + ", 100%, 50%)"; const draw2 = async (ary, tani) => { let avg = [0, 0, 0, 0, 0, 0, 0, 0, 0]; let _avg = [0, 0, 0, 0, 0, 0, 0, 0, 0]; let area = document.getElementById("container").children; await g.f(() => { for (let i = 0; i < ary.length; i++) { if (ary[i] && ary[i].length > 0) { avg[i] = 0; for (let j = 0; j < ary[i].length; j++) { avg[i] += (ary[i][j] | 0); } //少数点誤差を文字列で対処 let m1 = Math.floor((avg[i] / ary[i].length)); let m2 = Math.floor(100*(avg[i] / ary[i].length)) * 0.01; let m3 = m2 - m1; let m4 = Math.floor(100 * m3); avg[i] = "" + m1 + "." + m4 + "<div style='display:inline;font-size:0.5em;'>" + tani + "</div>"; _avg[i] = ("" + m1 + "." + m4)|0 //avg[i] = "" + (Math.floor(100 * (avg[i] / ary[i].length)) * 0.01) + tani; } else { avg[i] = "NoData"; } } }); let CA = [ hsla(310, 70, 60, 0.5), hsla(280, 70, 60, 0.5), hsla(250, 70, 60, 0.5), hsla(210, 70, 60, 0.5), hsla(180, 70, 60, 0.5), hsla(150, 70, 60, 0.5), hsla(120, 70, 60, 0.5), hsla(90, 70, 60, 0.5), hsla(60, 70, 60, 0.5) ] let avgtmp = _avg; avgtmp.sort((a,b)=>{ return a-b; }) console.log(avgtmp,_avg) /*for (let i = CA.length - 1,tmp = CA[i],r = Math.floor(Math.random() * (i + 1)); i > 0; i--, tmp = CA[i],r = Math.floor(Math.random() * (i + 1))) { CA[i] = CA[r]; CA[r] = tmp; }*/ for (let i = 0, nums = checkary(avg); i < avg.length; i++) { area[i].innerHTML = avg[i]; if (nums[i].length > 0) { for (let j = 0; j < nums[i].length; j++) { CA[nums[i][j]] = CA[i]; } } if (avg[i] === "NoData") { area[i].style.cssText += "background-color: " + hsla(0, 0, 50, 0.5) + " !important;"; } else { area[i].style.cssText += "background-color: " + CA[i] + " !important;"; } } } //配列の同じ要素がある場合はそれのindexを配列で返す. //返り血の例[[],[],[1,2],[],[1],...] const checkary = (a) => { let ans = []; for (let i = 0, tmp = []; i < a.length; i++, tmp = []) { for (let j = 0; j < a.length; j++) { if (i !== j && a[j] === a[i]) { tmp.push(j) } } ans.push(tmp); } return ans; } const hsla = (h, l, s, a) => { return "hsl(" + h + "," + l + "%," + s + "%," + a + ")"; } g.addEventListener('load',()=>{ common.socket = io.connect(); common.socket.on('connect', (data) => { common.socket.emit('test', "プレビュー接続完了"); common.socket.on("data", (data) => { common.socket.emit('test', "プレビュー受信完了"); if(data && data.name && data.metric){ (async () => { let x = g.data1.timestamps; console.log(data) switch(data.name){ case "気圧[hPa]": case "湿度[%]": case "照度[lx]": case "UVI[UV]": case "騒音[dB]": case "温度[℃]": case "WBGT(暑さ指数)": case "不快指数": console.log("描画!") //await re_draw1(x, g.data1[data.name], "日時", data.name, "chart2"); await draw2([ [], [], [], g.data1[data.name], [], g.data2[data.name], [], [], [] ], "(" + data.name + ")"); break; case "総人数": let d = [0, 0, 0, 0, 0, 0, 0, 0, 0], dd = g.data3; await g.f(() => { for (let i = 0,t = 0; i < d.length; i++,t = 0) { d[i] = []; for(let j = 0;j < dd["エリア" + (i + 1)].length;j++){ t += (dd["エリア" + (i + 1)][j])|0; } d[i].push(t); } console.log(d) }); await draw2(d, "人") } })(); } }); }); }) })(this);
import React, { Component } from 'react'; import HitList from './HitList'; import MyNav from './MyNav'; import ColorComponent from './ColorComponent'; import './App.css'; class App extends Component { render() { return ( <div> <MyNav /> <HitList /> <ColorComponent /> </div> ); } } export default App;
import React from 'react'; import BannerSection from './BannerSection'; import HeaderSection from './HeaderSection'; import BannerHolder from './BannerHolder/BannerHolder'; const LandingPage = () => <> <HeaderSection /> <BannerSection /> <BannerHolder /> </> export default LandingPage;
"use strict"; test('to be successful', function () { expect(2).toBe(2); });
// Queue contructor function function Queue() { this.result = []; this.head = 0; this.tail = 0; } Queue.prototype.enqueue = function(value) { this.result[this.tail] = value; this.tail++; } Queue.prototype.dequeue = function() { if (!this.size()) return; var value = this.result[this.head]; if (this.head > 99) { this.result = this.result.slice(this.head); this.tail = this.tail - this.head; this.head = 0; } this.head++; return value; } Queue.prototype.size = function() { return this.tail - this.head; };
const express=require("express"); const app=new express(); const port = process.env.PORT ||5000; const nav=[ {link:'/home',name:'Home'}, {link:'/books',name:'Books'}, {link:'/authors',name:'Authors'}, {link:'/addbook',name:'Add Book'}, {link:'/addauthor',name:'Add Author'}, {link:'/logout',name:'Log Out'}, // {link:'/login',name:'Log In'} ]; const BooksRouter=require('./src/routes/bookRoutes')(nav); const AuthorsRouter=require('./src/routes/authorRoutes')(nav); const addbookRouter = require('./src/routes/addbookRoutes')(nav); const addauthorRouter =require('./src/routes/addauthorRoutes')(nav); const loginRouter =require('./src/routes/loginRoutes')(nav); const signupRouter=require('./src/routes/signupRoutes')(nav); app.use(express.static('./public')); app.set('view engine','ejs'); app.set('views','./src/views'); app.use('/signup',signupRouter); app.use('/login',loginRouter); app.use('/books',BooksRouter); app.use('/authors',AuthorsRouter); app.use('/addbook',addbookRouter); app.use('/addauthor',addauthorRouter); app.get('/',function(req,res){ res.render("login", { nav, title:'Library'}); }); app.get('/logout',function(req,res){ res.render("login", { nav, title:'Library'}); }); app.get('/home',function(req,res){ res.render("index", { nav, title:'Library'}); }); app.listen(port,()=>{console.log("Server Ready at"+port)});
/** * Service */ angular.module('ngApp.home').factory('HomeService', function ($http, config, SessionService) { var bulkTracking = []; var ParcelHubTracking = function (carriertype,TrackingNo) { return $http.get(config.SERVICE_URL + '/Shipment/ParcelHubTracking', { params: { CarrierName: carriertype, TrackingNo: TrackingNo } }); }; var GettrackingDetail = function (carriertype, id) { return $http.get(config.SERVICE_URL + '/Shipment/GetTrackingdeatil', { params: { CarrierName: carriertype, TrackingNumber: id } }); }; var GetShipmentDetail = function (shipmentId) { return $http.get(config.SERVICE_URL + '/Shipment/GetShipmentDetail', { params: { shipmentId: shipmentId } }); }; var GetBulkTrackingDetails = function (BulkTrackingDetails) { return $http.post(config.SERVICE_URL + '/Shipment/GetBulkTrackingDetails', BulkTrackingDetails); }; var GetCarriers = function () { return $http.get(config.SERVICE_URL + '/Courier/GetUKCourier'); }; var GetCurrentOperationZone = function () { return $http.get(config.SERVICE_URL + '/OperationZone/GetCurrentOperationZone'); }; var IsManifestSupprt = function (userId) { return $http.get(config.SERVICE_URL + '/Manifest/IsManifestSupprt', { params: { userId :userId } }); }; return { GettrackingDetail: GettrackingDetail, GetCarriers: GetCarriers, GetBulkTrackingDetails: GetBulkTrackingDetails, bulkTracking: bulkTracking, ParcelHubTracking: ParcelHubTracking, GetCurrentOperationZone: GetCurrentOperationZone, IsManifestSupprt: IsManifestSupprt }; });
// app.js (API) const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); //specify where to find the schema //const ResearchProjects = require('./models/research') const Contractlist = require('./models/ContractProjects'); const Capstonelist = require('./models/CapstoneProjects'); const users = require('./models/Users'); const request = require('request'); // need this for 3rd party API call // connect and display the status mongoose.connect('mongodb+srv://capstone:capstone2020@capstoneprojectcluster-z3llo.mongodb.net/ccseprojects?retryWrites=true&w=majority', { useNewUrlParser: true }) .then(() => { console.log("connected"); }) .catch(() => { console.log("error connecting"); }); // use the following code on any request that matches the specified mount path app.use((req, res, next) => { // res.setHeader('Access-Control-Allow-Origin', '*'); //can connect from any host // res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, OPTIONS'); //allowable methods // res.setHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept'); res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization"); // Fix HTTP header issues when using authentication // https://stackoverflow.com/questions/32500073/request-header-field-access-control-allow-headers-is-not-allowed-by-itself-in-pr next(); }); // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })); // parse application/json app.use(bodyParser.json()); /**************************************** * capstone * ***************************************/ /* Requests for Capstone*/ /* Find all capstone Projects in database */ app.get('/capstoneprojects', (req, res, next) => { //call mongoose method find Capstonelist.find() //if data is returned, send data as a response .then(data => res.status(200).json(data)) //if error, send internal server error .catch(err => { console.log('Error: ${err}'); res.status(500).json(err); }); console.log('This is the response from capstone projects'); }); /* Find capstone projects by user */ app.get('/capstoneprojects/user/:id', (req, res, next) => { let id = req.params.id; //call mongoose method find (MongoDB db.Students.find()) Capstonelist.find({ userId: id }).sort('DateEntered') //if data is returned, send data as a response .then(data => res.status(200).json(data)) //if error, send internal server error .catch(err => { console.log('Error: ${err}'); res.status(500).json(err); }); console.log('This is the response from capstoneprojects/user'); }); app.get('/capstoneprojects/edit/:id', (req, res, next) => { //call mongoose method find let id = req.params.id; console.log('capstoneprojects/edit id is ' + id) Capstonelist.findById(id) //if data is returned, send data as a response .then(data => res.status(200).json(data)) //if error, send internal server error .catch(err => { console.log('Error: ${err}'); res.status(500).json(err); }); console.log('This is the response from capstoneprojects/edit'); }); app.post('/capstoneprojects/add', (req, res, next) => { // create a new project form variable and save request’s fields const Capstone = req.body; //sent an acknowledgment back to caller console.log('capstone post form:') console.log(Capstone) const Capstoneform = new Capstonelist({ userId: req.body.userId, ContactName: req.body.ContactName, ContactPhone: req.body.ContactPhone, ContactEmail: req.body.ContactEmail, JobTitle: req.body.JobTitle, CompanyName: req.body.CompanyName, Address: req.body.Address, Website: req.body.Website, ProjectTitle: req.body.ProjectTitle, Description: req.body.Description, Requirements: req.body.Requirements, MileStone1: req.body.MileStone1, MileStone2: req.body.MileStone2, Milestone3: req.body.Milestone3, BenefitStudent: req.body.BenefitStudent, BenefitSponsor: req.body.BenefitSponsor, Provide: req.body.Provide, Skill0: req.body.Skill0, Skill1: req.body.Skill1, Skill2: req.body.Skill2, Skill3: req.body.Skill3, Skill4: req.body.Skill4, Skill5: req.body.Skill5, Skill6: req.body.Skill6, Skill7: req.body.Skill7, Skill8: req.body.Skill8, Skill9: req.body.Skill9, RequireNDA: req.body.RequireNDA, RetainIP: req.body.RetainIP, WorkonSite: req.body.WorkonSite, SponsorSitePresentation: req.body.SponsorSitePresentation, CampusPresentation: req.body.CampusPresentation, VideoPresentation: req.body.VideoPresentation, NumberofTeams: req.body.NumberofTeams, sixToNineVirtual: req.body.sixToNineVirtual, sixToNineInPerson: req.body.sixToNineInPerson, nineToTwelveVirtual: req.body.nineToTwelveVirtual, nineToTwelveInPerson: req.body.nineToTwelveInPerson, twelveToThreeVirtual: req.body.twelveToThreeVirtual, twelveToThreeInPerson: req.body.twelveToThreeInPerson, threeToFiveVirtual: req.body.threeToFiveVirtual, threeToFiveInPerson: req.body.threeToFiveInPerson, AdditionalAvailability: req.body.AdditionalAvailability, DateEntered: req.body.DateEntered }); console.log('capstone object - Mongoose:') console.log(Capstoneform) //send the document to the database Capstoneform.save() //in case of success .then(() => { console.log('Success'); res.status(201).json({ 'capstoneform': 'project added successfully' }); }) //if error .catch(err => { console.log('Error:' + err); res.status(400).send("unable to save to database") }); //sent an acknowledgment back to caller //res.status(201).json('Post successful'); }); /* capstone projects update */ app.put('/capstoneprojects/update/:id', (req, res, next) => { console.log("/capstoneprojects/update id = " + req.params.id) // create a new capstone variable and save request’s fields const capstonef = req.body; //sent an acknowledgment back to caller console.log('capstone post form:') console.log(capstonef) if (mongoose.Types.ObjectId.isValid(req.params.id)) { //find a document and set updated field values Capstonelist.findOneAndUpdate({ _id: req.params.id }, { $set: { ContactName: req.body.ContactName, ContactPhone: req.body.ContactPhone, ContactEmail: req.body.ContactEmail, JobTitle: req.body.JobTitle, CompanyName: req.body.CompanyName, Address: req.body.Address, Website: req.body.Website, ProjectTitle: req.body.ProjectTitle, Description: req.body.Description, Requirements: req.body.Requirements, MileStone1: req.body.MileStone1, MileStone2: req.body.MileStone2, Milestone3: req.body.Milestone3, BenefitStudent: req.body.BenefitStudent, BenefitSponsor: req.body.BenefitSponsor, Provide: req.body.Provide, Skill0: req.body.Skill0, Skill1: req.body.Skill1, Skill2: req.body.Skill2, Skill3: req.body.Skill3, Skill4: req.body.Skill4, Skill5: req.body.Skill5, Skill6: req.body.Skill6, Skill7: req.body.Skill7, Skill8: req.body.Skill8, Skill9: req.body.Skill9, RequireNDA: req.body.RequireNDA, RetainIP: req.body.RetainIP, WorkonSite: req.body.WorkonSite, SponsorSitePresentation: req.body.SponsorSitePresentation, CampusPresentation: req.body.CampusPresentation, VideoPresentation: req.body.VideoPresentation, NumberofTeams: req.body.NumberofTeams, sixToNineVirtual: req.body.sixToNineVirtual, sixToNineInPerson: req.body.sixToNineInPerson, nineToTwelveVirtual: req.body.nineToTwelveVirtual, nineToTwelveInPerson: req.body.nineToTwelveInPerson, twelveToThreeVirtual: req.body.twelveToThreeVirtual, twelveToThreeInPerson: req.body.twelveToThreeInPerson, threeToFiveVirtual: req.body.threeToFiveVirtual, threeToFiveInPerson: req.body.threeToFiveInPerson, AdditionalAvailability: req.body.AdditionalAvailability, DateEntered: req.body.DateEntered } }, { new: true }) .then((results) => { if (results) { //what was updated console.log('capstone update results') console.log(results); res.status(200).json("Updated!"); } else { console.log("no data exist for this id"); } }) .catch((err) => { console.log('capstone update error') console.log(err); }); } else { console.log("please provide correct id"); } }); /* delete project */ //:id is a dynamic parameter that will be extracted from the URL app.delete("/capstoneprojects/:id", (req, res, next) => { console.log('app.js deletecapstone - id = ' + req.params.id) Capstonelist.deleteOne({ _id: req.params.id }).then(result => { console.log(result); res.status(200).json("Deleted!"); }); }); /********************************** * Contract Projects ****************************/ /* Requests for Contract*/ /* Find all contract Projects in database */ app.get('/contractprojects', (req, res, next) => { //call mongoose method find Contractlist.find() //if data is returned, send data as a response .then(data => res.status(200).json(data)) //if error, send internal server error .catch(err => { console.log('Error: ${err}'); res.status(500).json(err); }); console.log('This is the response from contract projects'); }); /* Find contract projects by user */ app.get('/contractprojects/user/:id', (req, res, next) => { let id = req.params.id; //call mongoose method find (MongoDB db.Students.find()) Contractlist.find({ userId: id }).sort('DateEntered') //if data is returned, send data as a response .then(data => res.status(200).json(data)) //if error, send internal server error .catch(err => { console.log('Error: ${err}'); res.status(500).json(err); }); console.log('This is the response from contractprojects/user'); }); app.get('/contractprojects/edit/:id', (req, res, next) => { //call mongoose method find let id = req.params.id; console.log('contractprojects/edit id is ' + id) Contractlist.findById(id) //if data is returned, send data as a response .then(data => res.status(200).json(data)) //if error, send internal server error .catch(err => { console.log('Error: ${err}'); res.status(500).json(err); }); console.log('This is the response from contractprojects/edit'); }); app.post('/contractprojects/add', (req, res, next) => { // create a new project form variable and save request’s fields const Contract = req.body; //sent an acknowledgment back to caller console.log('contract post form:') console.log(Contract) const Contractform = new Contractlist({ CompanyName: req.body.CompanyName, CompanyAddress: req.body.CompanyAddress, CompanyTitle: req.body.CompanyTitle, AgreedDate: req.body.AgreedDate, PaymentOnStart: req.body.PaymentOnStart, PaymentOnCompletion: req.body.PaymentOnCompletion, TotalAmount: req.body.TotalAmount, Sponsor: req.body.Sponsor, Organization: req.body.Organization, JobTitle: req.body.JobTitle, SponsorUserid: req.body.SponsorUserid, TermStartDate: req.body.TermStartDate, TermEndDate: req.body.TermEndDate, DateEntered: req.body.DateEntered }); console.log('contract object - Mongoose:') console.log(Contractform) //send the document to the database Contractform.save() //in case of success .then(() => { console.log('Success'); res.status(201).json({ 'contractform': 'project added successfully' }); }) //if error .catch(err => { console.log('Error:' + err); res.status(400).send("unable to save to database") }); //sent an acknowledgment back to caller //res.status(201).json('Post successful'); }); /* capstone projects update */ app.put('/contractprojects/update/:id', (req, res, next) => { console.log("/contractprojects/update id = " + req.params.id) // create a new contract variable and save request’s fields const contractf = req.body; //sent an acknowledgment back to caller console.log('contract post form:') console.log(contractf) if (mongoose.Types.ObjectId.isValid(req.params.id)) { //find a document and set updated field values Contractlist.findOneAndUpdate({ _id: req.params.id }, { $set: { CompanyName: req.body.CompanyName, CompanyAddress: req.body.CompanyAddress, CompanyTitle: req.body.CompanyTitle, AgreedDate: req.body.AgreedDate, PaymentOnStart: req.body.PaymentOnStart, PaymentOnCompletion: req.body.PaymentOnCompletion, TotalAmount: req.body.TotalAmount, Sponsor: req.body.Sponsor, Organization: req.body.Organization, JobTitle: req.body.JobTitle, SponsorUserid: req.body.SponsorUserid, TermStartDate: req.body.TermStartDate, TermEndDate: req.body.TermEndDate, DateEntered: req.body.DateEntered } }, { new: true }) .then((results) => { if (results) { //what was updated console.log('contract update results') console.log(results); res.status(200).json("Updated!"); } else { console.log("no data exist for this id"); } }) .catch((err) => { console.log('contract update error') console.log(err); }); } else { console.log("please provide correct id"); } }); /* delete project */ //:id is a dynamic parameter that will be extracted from the URL app.delete("/contractprojects/:id", (req, res, next) => { console.log('app.js deletecontract - id = ' + req.params.id) Contractlist.deleteOne({ _id: req.params.id }).then(result => { console.log(result); res.status(200).json("Deleted!"); }); }); /************************************ * USER LOGIN AND REGISTRATION * ***********************************/ /* User Login and Registration*/ app.get("/users/authenticate/:username/:password", (req, res, next) => { users.find({ username: req.params.username, password: req.params.password }) .then(result => { const user = { username: result[0].username, firstName: result[0].Firstname, lastName: result[0].Lastname } console.log(user); res.status(200).json(user); }) .catch(err => { console.log('Authentication Error: ${err}'); userFriendlyMsg = 'Cannot authenticate userid/password.' console.log(userFriendlyMsg) res.status(500).json(userFriendlyMsg); }); }); app.get("/users", (req, res, next) => { users.find().then(data => res.status(200).json(data)) .catch(err => { console.log('Error: ${err}'); res.status(500).json(err); }); }); app.post('/Users/register', (req, res, next) => { // const feedback = req.body; const userrecord = new users({ Firstname: req.body.firstname, Lastname: req.body.lastName, username: req.body.username, password: req.body.password }); console.log('users/register') console.log(userrecord) userrecord.save() .then(() => { console.log('Success'); }) .catch(err => { console.log('Error:' + err); }); //sent an acknowledgment back to caller console.log('user post form:') console.log(userrecord) res.status(201).json('Post successful'); }); /* end requests User/authentication */ //to use this middleware in other parts of the application module.exports = app;
import { Meteor } from 'meteor/meteor'; import { check, Match } from 'meteor/check'; import winston from 'winston'; import path from 'path'; import fs from 'fs'; const env = process.env.NODE_ENV || 'development'; let logDirectory = process.env.LOG_PATH || 'log'; if (!path.isAbsolute(logDirectory)) { const rootPath = path.resolve('.'); const absolutePath = rootPath.split(path.sep + '.meteor')[0]; logDirectory = path.resolve(absolutePath + path.sep + logDirectory); } // else: nothing todo, path already resolved if (!fs.existsSync(logDirectory)) { fs.mkdirSync(logDirectory); } // else: nothing todo, directory already exist // Timestamp setting const tsFormat = () => (new Date()).toLocaleTimeString(); // Logger configuration instance const logger = new (winston.Logger)({ transports: [ new (require('winston-daily-rotate-file'))({ filename: `${logDirectory}/-results.log`, timestamp: tsFormat, datePattern: 'yyyy-MM-dd', prepend: true, level: env === 'development' ? 'debug' : 'info' }) ] }); export const severity = { EMERG: 'emerg', ALERT: 'alert', CRIT: 'crit', ERROR: 'error', WARNING: 'warning', NOTICE: 'Notice', INFO: 'info', DEBUG: 'debug' }; export default logger;
const express = require('express'); const router = express.Router(); const isAdmin = require('../middleware/is-admin'); const adminController = require('../controllers/administrator'); //get all users router.get('/users', isAdmin, adminController.getAllUsers); //get a single user router.get('users/:userId', isAdmin, adminController.getUser); //toggle user is verified or not router.post('users/verify/:userId', isAdmin, adminController.toggleVerifyUser); //toggle user is authorized router.post('users/authorized/:userId', isAdmin, adminController.toggleIsAuthorized); //toggle is user profile complete router.post('users/complete/:userId', isAdmin, adminController.toggleIsProfileComplete); module.exports = router;
import React, { Component } from 'react' import NavBar from "./nav/NavBar.jsx" import ApplicationManager from "./ApplicationManager.jsx" import APICalls from "../modules/APICalls" import firebase from "firebase" import './reactManager.css' import ReactHtmlParser from 'react-html-parser'; let storage = firebase.storage() export default class ReactManager extends Component { state = { pageLoaded: false, //Login loggedIn: false, //need to reset with login currentUser: { userId: 1 }, songs: [], playlists: [], songs_playlists: [], songwriter: '', //new song form uploader: 0, uploadedFileName: "", songDownloadURL: "", songTitleInput: "", songLyricInput: "", songCoWriters: "", songDuration: "", //edit song editSongButtonClick: 0, editSongTitleInput: "", editSongLyricInput: "", editSongCoWriters: "", editSongDuration: "", //playlists newPlaylistText: "", editTitleButtonClicked: 0, editPlaylistTitle: "", //Sign Up signUpNameInput: "", signUpEmailInput: "", signUpPassword: "" } displayStringAsHTML = (htmlString) => { return <div>{ReactHtmlParser(htmlString)}</div>; } //Login/out --------------------------------------------------------------------------------------------- logout = () => { sessionStorage.removeItem('id') } //Sign Up ---------------------------------------------------------------------------------------- signUpSave = () => { APICalls.getAllFromJson("users") .then(data => { data.forEach(user => { if(user.email===this.state){ return alert("Account with that email already exists") } }) APICalls.saveToJson("users",{ name: this.state.signUpNameInput, email: this.state.signUpEmailInput, password: this.state.signUpPassword }).then(data => { sessionStorage.setItem("id", data.id) this.refreshData() }) }) } refreshData = () => { let stateSetter = {} APICalls.getEmbedFromJson("songs", 'songs_playlists', sessionStorage.getItem("id")) .then(data => { stateSetter.songs = data; return APICalls.getEmbedFromJson('playlists', 'songs_playlists', sessionStorage.getItem("id")) }) .then(data => { stateSetter.playlists = data; return APICalls.getFromJsonForUser("songs_playlists", sessionStorage.getItem("id")) }) .then(data => { stateSetter.editTitleButtonClicked = 0; stateSetter.songs_playlists = data; return APICalls.getOneFromJson("users", sessionStorage.getItem("id")) }) .then(data => { stateSetter.songwriter = data.name this.setState(stateSetter) this.setState({ pageLoaded: true }) }) } handleFieldChange = (evt) => { const stateToChange = {} stateToChange[evt.target.id] = evt.target.value this.setState(stateToChange) } editFieldChange = (value) => { this.setState({editSongLyricInput: value}) } newFieldChange = (value) => { this.setState({songLyricInput: value}) } componentDidMount() { this.refreshData(); } //Songs----------------------------------------------------------------------------------------------------- //uploading a song to firebase fileUploader = (e) => { let file = e.target.files[0]; //file name to save in database let fileName = file.name //reference to the file location on firebase let uploadedSong = firebase.storage().ref(file.name) //uploading the song let task = uploadedSong.put(file) //an open connection to the status of that upload task.on('state_changed', (snapshot) => { let progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100; console.log('Upload is ' + progress + '% done'); switch (snapshot.state) { case firebase.storage.TaskState.PAUSED: console.log('Upload is paused'); break; case firebase.storage.TaskState.RUNNING: console.log('Upload is running'); break; } }, (error) => { console.log(error) }, () => { //getting the download url task.snapshot.ref.getDownloadURL().then((downloadURL) => { //setting the download url and file name to state this.setState({ uploadedFileName: fileName, songDownloadURL: downloadURL }) }) }) }; //someone submits a new song newSongSave = () => { let songObj = { title: this.state.songTitleInput, fileName: this.state.uploadedFileName, userId: Number(sessionStorage.getItem("id")), downloadURL: this.state.songDownloadURL, lyric: this.state.songLyricInput, coWriters: this.state.songCoWriters, duration: this.state.songDuration } APICalls.saveToJson("songs", songObj) .then(() => APICalls.getEmbedFromJson("songs", 'songs_playlists', sessionStorage.getItem("id")).then(data => { this.setState({ songs: data, songTitleInput: "", uploadedFileName: "", songDownloadURL: "", songLyricInput: "", songCoWriters: "", songDuration: "" }) })) } //deleteSongs deleteSongClick = (evt) => { const idOfSongArray = evt.target.id.split('-'); //test APICalls.getOneFromJson("songs", idOfSongArray[1]) .then(data => { console.log("file name", data.fileName) let songRef = storage.ref(data.fileName); songRef.delete().then(() => { console.log("file deleted") }).catch((error) =>{ console.log(error) }); }) APICalls.deleteItem("songs", idOfSongArray[1]) .then(() => APICalls.getFromJsonForUser("songs", sessionStorage.getItem("id")).then(data => { this.setState({ songs: data }) } )) } //editSongs editSongClick = (e) => { let songId = e.target.id.split('-') APICalls.getOneFromJson("songs", Number(songId[1])) .then(data => this.setState({ editSongButtonClick: Number(songId[1]), editSongTitleInput: data.title, editSongLyricInput: data.lyric, editSongCoWriters: data.coWriters, editSongDuration: data.duration, })) } editSongSave = () => { APICalls.updateItem("songs", this.state.editSongButtonClick, { title: this.state.editSongTitleInput, lyric: this.state.editSongLyricInput, coWriters: this.state.editSongCoWriters, duration: this.state.editSongDuration }).then(() => APICalls.getEmbedFromJson("songs", 'songs_playlists', sessionStorage.getItem("id")) .then(data => { this.setState({ songs: data, editSongButtonClick: 0 }) })) } backSongClick = (e) => { this.setState({editSongButtonClick: 0}) } //Playlists----------------------------------------------------------------------------------------- moveSongUp = (evt) => { //first number is position number, second number is id number const relationshipArray = evt.target.id.split('-'); const positionNumb = Number(relationshipArray[1]) const relationshipId = Number(relationshipArray[2]) const playlistId = Number(relationshipArray[3]) const otherSongToChange = this.state.songs_playlists.filter(relationship => relationship.playlistId === playlistId && relationship.position === positionNumb -1) APICalls.updateItem('songs_playlists', relationshipId, {position: positionNumb-1}) .then(() => APICalls.updateItem('songs_playlists', otherSongToChange[0].id, {position: otherSongToChange[0].position+1}) .then(() => this.refreshData())) } moveSongDown = (evt) => { //first number is position number, second number is id number const relationshipArray = evt.target.id.split('-'); const positionNumb = Number(relationshipArray[1]) const relationshipId = Number(relationshipArray[2]) const playlistId = Number(relationshipArray[3]) const otherSongToChange = this.state.songs_playlists.filter(relationship => relationship.playlistId === playlistId && relationship.position === positionNumb +1) APICalls.updateItem('songs_playlists', relationshipId, {position: positionNumb+1}) .then(() => APICalls.updateItem('songs_playlists', otherSongToChange[0].id, {position: otherSongToChange[0].position-1}) .then(() => this.refreshData())) } addSongToPlaylist = (evt) => { const idOfSong = Number(evt.target.value); const idOfPlaylistArray = evt.target.id.split('-'); const idOfPlaylist = Number(idOfPlaylistArray[1]) //gather the number of songs in the playlist let playlistSongs = this.state.playlists.filter(playlist => playlist.id === idOfPlaylist) let songsArrayLength = playlistSongs[0].songs_playlists.length APICalls.saveToJson('songs_playlists', { songId: idOfSong, playlistId: idOfPlaylist, position: songsArrayLength + 1 }).then(() => this.refreshData()) } deleteSongFromPlaylist = (evt) => { //first number is position number, second number is id number const idOfPlaylistArray = evt.target.id.split('-'); const idOfPlaylist = Number(idOfPlaylistArray[3]) const relId = Number(idOfPlaylistArray[2]) const idOfSong = Number(idOfPlaylistArray[4]); const arrayOfSongs = this.state.songs_playlists.filter(relationship => relationship.playlistId === idOfPlaylist) const objOfCorrectRelationship = arrayOfSongs.filter(relationship => relationship.songId === idOfSong) let deletedSongPosition = objOfCorrectRelationship[0].position let promises = arrayOfSongs.filter(song => { //deletes the selected song if (song.songId === idOfSong){ return APICalls.deleteItem('songs_playlists', song.id) } //changes the position number of the songs in the playlists else if(song.position > deletedSongPosition){ return APICalls.updateItem("songs_playlists", song.id, {position: (song.position-1)}) } } ) Promise.all(promises).then(this.refreshData()) } removeSongFromPlaylist = (evt) => { const idOfSong = Number(evt.target.value); const idOfPlaylistArray = evt.target.id.split('-'); const idOfPlaylist = Number(idOfPlaylistArray[1]) const arrayOfSongs = this.state.songs_playlists.filter(relationship => relationship.playlistId === idOfPlaylist) const objOfCorrectRelationship = arrayOfSongs.filter(relationship => relationship.songId === idOfSong) let deletedSongPosition = objOfCorrectRelationship[0].position let promises = arrayOfSongs.filter(song => { //deletes the selected song if (song.songId === idOfSong){ return APICalls.deleteItem('songs_playlists', song.id) } //changes the position number of the songs in the playlists else if(song.position > deletedSongPosition){ return APICalls.updateItem("songs_playlists", song.id, {position: (song.position-1)}) } } ) Promise.all(promises).then(this.refreshData()) } addPlaylist = () => { APICalls.saveToJson("playlists", { title: this.state.newPlaylistText, userId: Number(sessionStorage.getItem("id")), passKey: (Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)), }).then(() => this.refreshData()) } removePlaylist = (evt) => { const idOfPlaylistArray = evt.target.id.split('-'); console.log(evt.target.id) const arrayOfSongsinPlaylist = this.state.songs_playlists.filter(relationship => relationship.playlistId === Number(idOfPlaylistArray[1])) console.log(arrayOfSongsinPlaylist) let arrayOfPromises = arrayOfSongsinPlaylist.map(relationship => { return APICalls.deleteItem("songs_playlists", relationship.id) }) Promise.all(arrayOfPromises).then(() => APICalls.deleteItem("playlists", idOfPlaylistArray[1])).then(() => this.refreshData()) } editPlaylistTitle = (evt) => { APICalls.updateItem("playlists", this.state.editTitleButtonClicked, { title: this.state.editPlaylistTitle }) .then(() => this.refreshData()) } editTitleButton = (evt) => { const idOfPlaylistArray = evt.target.id.split('-'); APICalls.getOneFromJson('playlists', Number(idOfPlaylistArray[1])) .then(playlist => { this.setState({ editTitleButtonClicked: Number(idOfPlaylistArray[1]), editPlaylistTitle: playlist.title }) }) } editTitleBackButton = () => { this.setState({ editTitleButtonClicked: false }) } render() { if (this.state.pageLoaded) return ( <div className="container"> <div className="row"> <div className="col-2"> <NavBar passedState={this.state} logout = {this.logout}/> </div> <div className="col-8 container mainContainer"> <ApplicationManager passedState={this.state} refreshData={this.refreshData} signUpSave={this.signUpSave} displayStringAsHTML={this.displayStringAsHTML} //playlists addSongToPlaylist={this.addSongToPlaylist} addPlaylist={this.addPlaylist} removeSongFromPlaylist={this.removeSongFromPlaylist} removePlaylist={this.removePlaylist} editTitleButton={this.editTitleButton} editTitleBackButton={this.editTitleBackButton} editPlaylistTitle={this.editPlaylistTitle} newFieldChange={this.newFieldChange} deleteSongFromPlaylist={this.deleteSongFromPlaylist} //songs deleteSongClick={this.deleteSongClick} fileUploader={this.fileUploader} handleFieldChange={this.handleFieldChange} newSongSave={this.newSongSave} editSongClick={this.editSongClick} backSongClick = {this.backSongClick} editSongSave={this.editSongSave} editFieldChange={this.editFieldChange} moveSongUp = {this.moveSongUp} moveSongDown = {this.moveSongDown} /> </div> </div > </div> ) else { return (<p> page loading....</p >) } } }
import to from 'await-to-js'; import { BASE_URL } from './index.js' /** * REST Query, Get Review by id * @param {id} * @return Error object or review object */ export const GetReview = async(id) => { let error, response; [error, response] = await to(fetch(`${BASE_URL}/reviews/${id}`, { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } })); if(error) { console.error(error); return {error: error} } else { switch (response.status) { case 200: case 201: let review = await response.json(); return review; case 401: return {error: 'Unauthorized'} case 404: return {error: 'Review not found'} default: return {error: `Unexpected server response code of ${response.status}`} } } } /** * REST Query, Update review by id * @param {id,rating,title,reviewBody,flagged} * @return Error object or review object */ export const UpdateReview = async(id,rating,title,reviewBody,flagged) => { let body = { rating: rating, title: title, body: reviewBody, flagged: flagged } let error, response; [error, response] = await to(fetch(`${BASE_URL}/reviews/${id}`, { method: 'PUT', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(body) })); if(error) { console.error(error); return {error: error} } else { switch (response.status) { case 201: case 200: let review = await response.json(); return review; case 404: return {error: 'Review not found'} default: return {error: `Unexpected server response code of ${response.status}`} } } } /** * REST Query, Delete review by id * @param {id} * @return Error object or review object */ export const DeleteReview = async(id) => { let error, response; [error, response] = await to(fetch(`${BASE_URL}/reviews/${id}`, { method: 'DELETE', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } })); if(error) { console.error(error); return {error: error} } else { switch (response.status) { case 200: case 201: let review = await response.json(); return review; case 404: return {error: 'Review not found'} default: return {error: `Unexpected server response code of ${response.status}`} } } } /** * REST Query, Get all reviews * @param {id} * @return Error object or review list of objects */ export const GetAllReviews = async() => { let error, response; [error, response] = await to(fetch(`${BASE_URL}/reviews`, { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } })); if(error) { console.error(error); return {error: error} } else { switch (response.status) { case 200: case 201: let reviews = await response.json(); return reviews; default: return {error: `Unexpected server response code of ${response.status}`} } } } /** * REST Query, Submit review * @param {poiID,rating,title,reviewBody,author} * @return Error object or review object */ export const SubmitReview = async(poiID,rating,title,reviewBody,author) => { let body = { poi: poiID, rating: rating, title: title, body: reviewBody, author: author, flagged: false } let error, response; [error, response] = await to(fetch(`${BASE_URL}/reviews`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify(body) })); if(error) { console.error(error); return {error: error} } else { switch (response.status) { case 201: case 200: let review = await response.json(); return review; case 401: return {error: 'Unauthorized'} case 409: return {error: 'Review Conflict'} default: return {error: `Unexpected server response code of ${response.status}`} } } } /** * REST Query, Get reviews by POI id * @param {poiID} * @return Error object or review list of objects */ export const GetReviewsByPOI = async(poiID) => { let error, response; [error, response] = await to(fetch(`${BASE_URL}/reviews/poi/${poiID}`, { method: 'GET', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' } })); if(error) { console.error(error); return {error: error} } else { switch (response.status) { case 200: case 201: let review = await response.json(); return review; case 401: return {error: 'Unauthorized'} case 404: return {error: `POI with id: ${poiID} not found`} default: return {error: `Unexpected server response code of ${response.status}`} } } }
'use strict'; function Range( min, max, n ) { if ( n === void 0 ) { n = 2; } // throw 'The min and max must be numbers' if isNaN(@min) or ! _.isNumber(@min) or isNaN(@max) or ! _.isNumber(@max) if ( n < 2 ) { throw 'The range must include at least 2 values, a min and max'; } if ( max < min ) { throw 'The max (' + max + ') must be greater than the min (' + min + ')'; } this.min = min; this.max = max; this.n = n; } Range.prototype = { getValues: function() { var separation = ( this.max - this.min ) / ( this.n - 1 ); for( var values = [], i = 0, l = this.n - 1; i < l; i++ ) { values.push( this.min + separation * i ); } return values; }, getWidth: function() { return this.max - this.min; } }; module.exports = Range;
tablePopulate(); // vehicle input command $('#vehSubmit').on('click', function() { event.preventDefault(); var brand = $('#brand').val().trim(); if (brand === 'genesis') { var search = new Array(); $.ajax({ url: "api/genvehlists", datatype: 'json', success: function(rows) { rows.forEach(function(row) { if (search.indexOf(row.id) == -1) { search.push(row.id); } }) // console.log(search); var lastId = search.pop(); // console.log(lastId); genVehInput(lastId); // console.log(data.id) } }); // alert('genesis') } else { if (brand === 'hyundai') { // alert('hyundai') } } }) function genVehInput(lastId) { // console.log(lastId); var genId = parseInt(lastId) + 1; var modId = Math.floor(Math.random() * 500); var modelIn = $("#mod_code").val().trim(); var modelCodeUp = modelIn.toUpperCase(); var nameIn = $("#mod_name").val().trim(); var nameUp = nameIn.toUpperCase(); var netIdIn = $("#net_id").val().trim(); var netIdUp = netIdIn.toUpperCase(); var trMin = $("#term_m").val().trim(); var trMup = trMin.toUpperCase(); var trFin = $("#term_f").val().trim(); var trFup = trFin.toUpperCase(); var testLocIn = $("#test_loc").val().trim(); var testLocUp = testLocIn.toUpperCase(); var newGen = { //brand = $("#brand").val().trim(), id: genId, model_num: modId, model_name: nameUp, model: modelCodeUp, start_year: $("#start_year").val().trim(), } var genVolt = { // id: genId, model: modelCodeUp, model_num: modId, start_year: $("#start_year").val().trim(), net_id: netIdUp, test_loc: testLocUp, volt_h: $("#can_h_v").val().trim(), volt_l: $("#can_l_v").val().trim(), } var genRes = { // id: genId, model_num: modId, model_name: nameUp, model: modelCodeUp, start_year: $("#start_year").val().trim(), net_id: netIdUp, res_val_m: $("#split_res_m").val().trim(), res_val_f: $("#split_res_f").val().trim(), tot_res: $("#tot_res").val().trim(), term_m: trMup, term_f: trFup, test_loc: testLocUp, pin_h: $("#pin_h").val().trim(), pin_l: $("#pin_l").val().trim(), trM_view1: $("#trM_img1").val().trim(), trM_view2: $("#trM_img2").val().trim(), trF_view1: $("#trF_img1").val().trim(), trF_view2: $("#trF_img2").val().trim(), } var genMedia = { model_num: modId, model_name: nameUp, model: modelCodeUp, model_img: $("#model_img").val().trim(), c_can_img: $("#c_can_img1").val().trim(), // c_can_img2: $("#c_can_img2").val().trim(), p_can_img1: $("#p_can_img1").val().trim(), p_can_img2: $("#p_can_img1").val().trim(), test_loc_img: $("#test_loc_img").val().trim(), conn_view1: $("#conn_view_img1").val().trim(), conn_view2: $("#conn_view_img1").val().trim(), } addGen(newGen); addGenRes(genRes); addGenVolt(genVolt); addGenMedia(genMedia) $('#brand').val("Brand Select"); $("#net_id").val("Network Select"); $("#mod_name").val(""); $("#mod_code").val(""); $("#start_year").val(""); $("#net_id").val(""); $("#can_h_v").val(""); $("#can_l_v").val(""); $("#split_res_m").val(""); $("#split_res_f").val(""); $("#tot_res").val(""); $("#term_m").val(""); $("#term_f").val(""); $("#test_loc").val(""); $("#pin_h").val(""); $("#pin_l").val(""); } // add vehicle function addGen(newGen) { return $.ajax({ headers: { "Content-Type": "application/json" }, type: "POST", url: "api/genvehlists", data: JSON.stringify(newGen), success: function() { // alert(newGen.model_name + ' has been added!'); } }) } // add network resitance info function addGenRes(genRes) { return $.ajax({ headers: { "Content-Type": "application/json" }, type: "POST", url: "api/gencanress", data: JSON.stringify(genRes), success: function() { // alert(genRes.model_name + ' has been added!'); } }) } // add network votage info function addGenVolt(genVolt) { return $.ajax({ headers: { "Content-Type": "application/json" }, type: "POST", url: "api/gencanvolts", data: JSON.stringify(genVolt), success: function() { // alert(genVolt.model + ' has been added!'); } }) } // add media info function addGenMedia(genMedia) { return $.ajax({ headers: { "Content-Type": "application/json" }, type: "POST", url: "api/genmedia", data: JSON.stringify(genMedia), success: function() { alert(genMedia.model_name + ' has been added!'); } }) } // user data population function tablePopulate() { //reset table $("#userTableBody").empty(); $.ajax({ url: "api/users", type: 'GET', success: function(data) { // console.log(data); for (let i = 0; i < data.length; i++) { tRow = $('<tr>'); var tCell1 = $('<td>').html(data[i].id); tCell1.attr('class', "id"); var tCell2 = $('<td>').html(data[i].user); tCell2.attr('class', "user"); var tCell3 = $('<td>').html(data[i].password); tCell3.attr('class', "password"); $("#userTableBody").append(tRow.append(tCell1, tCell2, tCell3)); } }, error: function() { alert('error'); } }); } // loading gif show/hide $(document).ready(function() { $(document).ajaxStart(function() { $("#userTableBody").hide(); $("#loading").show(); }).ajaxStop(function() { setTimeout(function() { $("#loading").hide(); $("#userTableBody").show(); }, 1000); }); }); // user add $('#userSubmit').on('click', function() { event.preventDefault(); var newUser = { user: $('#add_user').val().trim(), password: $('#pass_word').val().trim() }; var userCount = newUser.user.length; var passCount = newUser.password.length; if (!(newUser.user && newUser.password)) { alert("You must enter an username and password to add a new user!"); return; } else { if (userCount < 6 || passCount < 6) { alert('Please make sure user and/or password are 6 characters in length') return; } addUser(newUser); $('#add_user').val(""); $('#pass_word').val(""); } }); function addUser(newUser) { return $.ajax({ headers: { "Content-Type": "application/json" }, type: "POST", url: "api/users", data: JSON.stringify(newUser), success: function() { // alert(newUser.user + ' has been added!'); tablePopulate(); } }) } // user delete $('#delSubmit').on('click', function() { event.preventDefault(); // console.log('this ran'); var user = $('#del_user').val().trim(); if (!(user)) { alert("You must enter a username to remove!"); return; } delUser(user) $('#del_user').val(""); }); function delUser(user) { // alert(remove + ' has been removed'); return $.ajax({ type: "DELETE", url: "api/users", data: { user: user } }).then(function(rowDeleted) { if (rowDeleted === 1) { // alert(user + ' was deleted succesfully'); tablePopulate(); } }, function(err) { console.log(err); }); } //input length set and clear when clicked // $("input[placeholder]").each(function() { // $(this).attr('size', $(this).attr('placeholder').length); // }); $('.input').on('click focusin', function() { this.value = ''; }); //adding decimals to needed inputs $("#can_h_v").blur(function() { this.value = ((parseInt(this.value) * .01).toFixed(2)); }); $("#can_l_v").blur(function() { this.value = ((parseInt(this.value) * .01).toFixed(2)); }); $("#tot_res").blur(function() { this.value = ((parseInt(this.value) * .10).toFixed(2)); }); $("#split_res_m").blur(function() { this.value = ((parseInt(this.value) * .10).toFixed(2)); }); $("#split_res_f").blur(function() { this.value = ((parseInt(this.value) * .10).toFixed(2)); });
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' import store from './store' import ElementUi from 'element-ui' import './common/sass/element-variables.scss' import Mock from './mock/mock' // 全局样式 import './common/sass/common.scss' // font-awesome字体图标 import 'font-awesome/css/font-awesome.min.css' // request import {onPost, onGet, request} from './request/main' // 自定义工具函数 import * as utils from './common/js/utils' import * as jsonUtils from './common/js/jsonUtils' // 向后台传递日志信息 import * as updateLogs from './request/log/export' import dictCode from './common/js/dictCode' // 全局组件 import Icon from 'vue-svg-icon/Icon' import BDialog from './components/BaseDialog/BaseDialog' import BPagination from './components/BasePagination/index' // 按钮权限指令 import onlyBtnPermission from './directive/onlyBtnPermission' import multipleBtnPermission from './directive/multipleBtnPermission' Vue.use(onlyBtnPermission) Vue.use(multipleBtnPermission) // svg图标组件 Vue.component('icon', Icon) // 封装 element 弹框 Vue.component('b-dialog', BDialog) // 封装 element 分页 Vue.component('b-pagination', BPagination) // 数据模拟 Mock.init() Vue.use(ElementUi) // 绑定到Vue原型中方便使用 Vue.prototype.$request = request Vue.prototype.$post = onPost Vue.prototype.$get = onGet Vue.prototype.$utils = utils Vue.prototype.$jsonUtils = jsonUtils Vue.prototype.$updateLog = updateLogs Vue.prototype.$DICT_CODE = dictCode Vue.config.productionTip = false /* eslint-disable no-new */ window.$vm = new Vue({ el: '#app', router, store, components: { App }, template: '<App/>' })
var alexa = require("alexa-app"); var search = require('youtube-search'); var fs = require('fs'); var request = require('request'); var app = new alexa.app("youtube"); var searchOpts = { maxResults: 1, type: 'video', key: process.env.YOUTUBE_API_KEY }; var lastSearch; app.pre = function(req, response, type) { if (req.data.session !== undefined) { if (req.data.session.application.applicationId !== process.env.ALEXA_APPLICATION_ID) { response.fail("Invalid application"); } } else { if (req.applicationId !== process.env.ALEXA_APPLICATION_ID) { response.fail("Invalid application"); } } }; app.intent("GetVideoIntent", { "slots": { "VideoQuery": "VIDEOS", }, "utterances": [ "search for {-|VideoQuery}", "find {-|VideoQuery}", "play {-|VideoQuery}", "start playing {-|VideoQuery}", "put on {-|VideoQuery}" ] }, function(req, response) { return get_executable_promise(req, response, 'english'); } ); app.intent("GetVideoGermanIntent", { "slots": { "VideoQuery": "VIDEOS", }, "utterances": [ "suchen nach {-|VideoQuery}", "finde {-|VideoQuery}", "spielen {-|VideoQuery}", "anfangen zu spielen {-|VideoQuery}", "anziehen {-|VideoQuery}" ] }, function(req, response) { return get_executable_promise(req, response, 'german'); } ); function get_executable_promise(req, response, language) { var query = req.slot("VideoQuery"); console.log('Searching ... ' + query); return new Promise((resolve, reject) => { search(query, searchOpts, function(err, results) { if (err) { reject(err.message); } else if (results.length !== 1) { resolve({ message: language === 'german' ? 'Ich konnte deine Bitte in diesem Moment nicht abschließen.' : 'I could not complete your request at this moment.', url: null, metadata: null }); } else { var metadata = results[0]; if (metadata.id === undefined) { resolve({ message: language === 'german' ? 'Keine Ergebnisse auf Youtube gefunden.' : query + ' did not return any results on YouTube.', url: null, metadata: null }); } else { console.log('Found ... ' + metadata.title); var id = metadata.id; var externalDownload = 'https://dmhacker-youtube.herokuapp.com/alexa/' + id; request(externalDownload, function(err, res, body) { if (err) { reject(err.message); } else { lastSearch = JSON.parse(body).link; console.log('Stored @ '+lastSearch); resolve({ message: language === 'german' ? 'Läuft gerade: ' + metadata.title : 'Now playing: ' + metadata.title, url: lastSearch, metadata: metadata }); } }); } } }); }).then(function (content) { var message = content.message; var streamUrl = content.url; var metadata = content.metadata; response.say(message); if (streamUrl) { response.audioPlayerPlayStream('REPLACE_ALL', { 'url': streamUrl, 'streamFormat': 'AUDIO_MPEG', 'token': metadata.id, 'offsetInMilliseconds': 0 }); response.card({ 'type': 'Simple', 'title': 'Search for "' + query + '"', 'content': 'Alexa found "' + metadata.title + '" at ' + metadata.link + '.' }); } response.send(); }).catch(function(reason) { response.fail(reason); }); } app.audioPlayer("PlaybackStarted", function(request, response) { console.log('Playback started.'); }); app.audioPlayer("PlaybackFailed", function(request, response) { console.log('Playback failed.'); console.log(request.data.request); console.log(request.data.request.error); }); app.intent("AMAZON.PauseIntent", {}, function(req, response) { response.audioPlayerStop(); }); app.intent("AMAZON.ResumeIntent", {}, function(req, response) { if (lastSearch === undefined) { response.say('You were not playing any video previously.'); } else { response.audioPlayerPlayStream('ENQUEUE', { 'url': lastSearch, 'streamFormat': 'AUDIO_MPEG', 'token': constants.token, 'expectedPreviousToken': constants.expectedPreviousToken, 'offsetInMilliseconds': 0 }); } }); app.intent("AMAZON.StopIntent", {}, function(req, response) { lastSearch = undefined; response.audioPlayerStop(); response.audioPlayerClearQueue(); }); exports.handler = app.lambda();
import HalSerializer from "./ember-data-hal-9000/serializer"; import Ember from 'ember'; export default HalSerializer.extend({ init: function() { Ember.debug('Spring Boot: Loaded Custom Serializer'); return this._super.apply(this, arguments); }, extractArray: function(store, primaryType, rawPayload) { var typeKey = primaryType.typeKey; var mergedPayload = []; //merge subclasses into a single supertype record for (var property in rawPayload._embedded) { var originalValue = rawPayload._embedded[property]; var isOwnProperty = rawPayload._embedded.hasOwnProperty(property); //var isSubclassOfPrimaryType = true; var isArray = Ember.isArray(originalValue); //Check if the property is a subclass of the primaryType requested var collectionModelClass = property.singularize().dasherize(); var CollectionModel = store.modelFor(collectionModelClass); var isSubclassOfPrimaryType = CollectionModel instanceof primaryType.constructor; if (isOwnProperty && isSubclassOfPrimaryType && isArray) { mergedPayload.pushObjects(originalValue); delete rawPayload._embedded[property]; } } rawPayload._embedded[typeKey] = mergedPayload; return this._super(store, primaryType, rawPayload); }, serializeIntoHash: function(hash, type, record, options) { var serialized = this.serialize(record, options); // //Setup Self Link // serialized['_links'] = {}; // serialized['_links'].self = {}; // serialized['_links'].self.href = 'http://localhost:8080/hal' + '/' + relationshipType.type.pluralize() + '/' + record.id; //Iterate relationship and turn plain ID values into URL String type.eachRelationship(function(attribute) { var relationshipType = type.metaForProperty(attribute); if(relationshipType.kind === 'belongsTo') { serialized[attribute] = 'http://localhost:8080/hal' + '/' + relationshipType.type.pluralize() + '/' + record.get(attribute + '.id'); } }); //remove the root element Ember.merge(hash, serialized); } });
import { PLAYER, WINNERCOUNT } from "./constants"; const checkUp = (board, turn) => { // Loop through each column, loop through each row, start count when there is a hit let count = 0; let hasWinner = false; for (let col = 0; col < board.length; col++) { count = 0; for (let row = 0; row < board[col].length; row++) { if (board[col][row] === PLAYER[turn].icon) count++; else // It has to be consecutive, otherwise restart count count = 0; if (count === WINNERCOUNT) { // We have a winner, break out of loops row = board[col].length; hasWinner = true; } } if (hasWinner) col = board.length; } return hasWinner; } // TODO: I feel that this solution is not very efficient const checkAcross = (board, turn) => { // Loop through each column, loop through each row, when there is a hit, increment column index let count = 0; let hasWinner = false; for (let col = 0; col < board.length; col++) { count = 0; for (let row = 0; row < board[col].length; row++) { count = 0; if (board[col][row] === PLAYER[turn].icon) {// There is a hit for (let newCol = col; newCol < board.length; newCol++) { if (board[newCol][row] === PLAYER[turn].icon) count++; else // It has to be consecutive, otherwise restart count count = 0; if (count === WINNERCOUNT) { // We have a winner, break out of loops newCol = board.length; hasWinner = true; } } } else // It has to be consecutive, otherwise restart count count = 0; if (hasWinner) { // We have a winner, break out of loops row = board[col].length; } } if (hasWinner) col = board.length; } return hasWinner; } const checkDiag = (board, turn, direction) => { // Loop through each column, loop through each row, when there is a hit, increment column index let count = 0; let hasWinner = false; for (let col = 0; col < board.length; col++) { count = 0; for (let row = 0; row < board[col].length; row++) { count = 0; if (board[col][row] === PLAYER[turn].icon) {// There is a hit for (let newCol = col, newRow = row; newCol < board.length; newCol++) { if (board[newCol][newRow] === PLAYER[turn].icon) count++; else // It has to be consecutive, otherwise restart count count = 0; if (count === WINNERCOUNT) { // We have a winner, break out of loops newCol = board.length; hasWinner = true; } (direction === "up") ? newRow++ : newRow--; } } else // It has to be consecutive, otherwise restart count count = 0; if (hasWinner) { // We have a winner, break out of loops row = board[col].length; } } if (hasWinner) col = board.length; } return hasWinner; } const checkWinner = (board, turn) => { return checkDiag(board, turn, "down") || checkDiag(board, turn, "up") || checkAcross(board, turn) || checkUp(board, turn); ; } export default checkWinner;
import React from 'react' import RegisterForm from '../components/RegisterForm' import { Link } from 'react-router-dom' class Register extends React.Component { render() { return ( <section className="register"> <section className="register__container"> <h2>Regístrate</h2> <RegisterForm {...this.props}/> <Link to='/login'> Iniciar sesión </ Link> </section> </section> ) } } export default Register
export default { data: function() { return { querying: false, queryForm: { page: 1, pageSize: 10 }, queryResult: { total: 0 } } }, methods: { handlePageSizeChange(val) { this.queryForm.pageSize = val this.query() }, handlePageChange(val) { this.queryForm.page = val this.query() }, query() { this.querying = true this.queryPageData().finally(() => { this.querying = false }) } } }
//2 steps to create and object instance //first, declare the object variable var bug; //add a second object var jit; function setup() { createCanvas(200,200); background(170); //second, initialize the object with the keyword new //pass in the parameters for x, y, diam bug = new JitterBug(width/2, height/2, 20); jit = new JitterBug(width*.25, height*.25, 50); } function draw() { //call the methods //mirrors the way the are constructed using this. but now we use the object's variable name bug.move(); bug.display(); //the new object gets its own methods jit.move(); jit.display(); }
import React from 'react'; import Header from '../components/Header.jsx'; import AppGetter from '../components/AppGetter.jsx'; // App component - represents the whole app export default class HomePage extends React.Component { render() { return ( <div className="container"> <Header /> <AppGetter /> </div> ); } }
'use strict'; var Bet = require('../../app/bet'); describe('Bet validations', () => { it('should mandate for a bet type', (done) => { Bet.create((err) => { expect(err.message).to.equal('Product is mandatory'); done(); }); }); it('should mandate for a bet type even when containing only spaces', (done) => { Bet.create(' ', (err) => { expect(err.message).to.equal('Product is mandatory'); done(); }); }); it('should validate bet from 3 types W,P,E', (done) => { Bet.create('A', (err) => { expect(err.message).to.equal('Invalid product. Use W, P or E.'); done(); }); }); it('should mandate runner selection', (done) => { Bet.create('W', (err) => { expect(err.message).to.equal('Selections is mandatory'); done(); }); }); it('should mandate bet amount', (done) => { Bet.create('W', '2', (err) => { expect(err.message).to.equal('Stake is mandatory'); done(); }); }); it('should validate bet amount to be a whole number', (done) => { Bet.create('W', '2', 'a', (err) => { expect(err.message).to.equal('Stake needs to be a whole number greater than 0'); done(); }); }); it('should validate runner selection to be a whole number for place bet', (done) => { Bet.create('P', 'a', '1', (err) => { expect(err.message).to.equal('Selections must be whole numbers'); done(); }); }); it('should validate runner selection to be a whole number for wind bet', (done) => { Bet.create('W', 'a', '1', (err) => { expect(err.message).to.equal('Selections must be whole numbers'); done(); }); }); describe('ExactaBet validations', () => { it('should validate runner selection to be an array for exacta bet', (done) => { Bet.create('E', 'a', '1', (err) => { expect(err.message).to.equal('Exacta bet selections must be for first and second position'); done(); }); }); it('should validate runner selection to be an array of whole numbers for exacta bet', (done) => { Bet.create('E', ['a', '1'], '1', (err) => { expect(err.message).to.equal('Selections must be whole numbers'); done(); }); }); it('should validate runner selection to be an array of 2 whole numbers for exacta bet', (done) => { Bet.create('E', ['1'], '1', (err) => { expect(err.message).to.equal('Exacta bet selections must be for first and second position'); done(); }); }); }); });
module.exports = { production: false, v1: '/v1', v2: '/v2' }
import axios from "axios" export const logIn =(token)=>{ return async dispatch => { try{ const response= await axios.post('http://localhost:8888/back/api/validate_token.php',token) const json =await response.data.data dispatch({ type:"LOG_IN", id:+json.id, firstname:json.firstname, lastname:json.lastname, email:json.email, phone:json.phone, login:true }) return json } catch(error){ console.log(error); } } } export const logOut = ()=> ({ type: 'LOG_OUT' });
/* Esercizio 1 Dato un array di interi, restituire la loro somma fino a che non viene ritrovato un valore negativo */ Array.prototype.sumWhileNeg = function(){ var tot = 0; this.every(x => { if(x > 0){ tot += x; } return x > 0; } ) return tot; } /* Esercizio 3 Dato un array di 10 elementi, calcolarne la media */ Array.prototype.avg = function() { if(this.length == 0){ return 0; }else{ return this.reduce((acc, x) => acc + x, 0) / this.length; } } /* Esercizio 9 Dato una lista di elementi, scrivere un algoritmo che permetta di invertire l’ordine degli elementi. Esempio: Input: A = {2, 5, 8} Output A= {8, 5, 2} */ Array.prototype.reverse = function() { var b = []; var c = this.length - 1; for (var i = 0; i < this.length; i++){ b[c] = this[i]; c = c - 1; } return a = b; } /* Esercizio 11 Data una lista di interi A, si riordini gli elementi della lista in modo tale che tutti gli elementi dispari precedano nello stesso ordine tutti gli elementi pari. Esempio Input: A = {2, 5, 1, 8} Output: A = {5, 1, 2, 8} */ Array.prototype.concatOddEven = function() { var pari = this.filter(x => (x % 2 == 0)); var disp = this.filter(x => (x % 2 != 0)); return disp.concat(pari); } // Call ex for script. function ex_01(arr){ return arr.sumWhileNeg(); } function ex_03(arr){ return arr.avg(); } function ex_09(arr){ return arr.reverse(); } function ex_11(arr){ return arr.concatOddEven(); }
const express = require('express'); const bodyParser = require('body-parser'); const app = express(); const port = 9000; const queries = require("../model/queries.js"); //Initialize body barser app.use(bodyParser.json()); app.use( bodyParser.urlencoded({ extended: true, }) ); app.listen(port, () => { console.log(`App running on port ${port}.`) }); app.get('/users', queries.getAllUsers); app.get('/users/:userId', queries.getUserById); app.get('/users/projects/:userId', queries.getUsersProjects); app.get('/users/tasks/:userId/:projectId', queries.getUsersTasks); app.get('/tasks/:taskId', queries.getTask); app.get('/projects', queries.getAllProjects); app.get('/projects/tasks/:projectId', queries.getAllTasksForProject); //app.post('/login', queries.loginUser); app.post('/users', queries.createUser); app.post('/projects', queries.createProject); app.post('/tasks', queries.createTask);
class SortedList { constructor() { this.array = []; this.length = this.array.length; } add(item) { this.array.push(item); this.length = this.array.length; // sort array if (this.length > 1) { this.array.sort(function(n1, n2) { return n1 - n2; }); } } get(pos) { let index = pos - 1; // check negative index and outOfBound index if (index >= this.length || index < 0) { let error = new Error('OutOfBounds'); return error; } else { return this.array[index]; } } max() { if (this.length === 0) { let error = new Error('EmptySortedList'); return error; } else { return this.array[this.length - 1]; } } min() { if (this.length === 0) { let error = new Error('EmptySortedList'); return error; } else { return this.array[0]; } } sum() { if (this.length === 0) { return 0; } else { return this.array.reduce(function(acc, n) { return acc + n }, 0) } } average() { if (this.length === 0) { let error = new Error('EmptySortedList'); return error; } else { return this.sum() / this.length; } } } module.exports = SortedList;
import React from "react"; import { render, fireEvent, cleanup, waitForElement } from "react-testing-library"; import "jest-dom/extend-expect"; import "../ChannelForm"; import ChannelCreator from "../ChannelCreator"; afterEach(cleanup); const username = "test-user"; describe("When a user inputs a channel name that doesn't exist", () => { test("It should display the user's input", () => { const form = render(<ChannelCreator username={username} />); const input = form.getByLabelText("Name"); fireEvent.change(input, { target: { value: "ninjas-dancing" } }); expect(input.value).toBe("ninjas-dancing"); }); test("It should enable the submit button", () => { const form = render(<ChannelCreator username={username} />); const input = form.getByLabelText("Name"); fireEvent.change(input, { target: { value: "ninjas-dancing" } }); expect(form.getByText("Create Channel").disabled).not.toBeTruthy(); }); }); describe("When a user inputs a channel name that already exist", () => { test("It should display an error message", () => { const form = render( <ChannelCreator channels={["javascript", "python", "php7"]} username={username} /> ); const input = form.getByLabelText("Name"); fireEvent.change(input, { target: { value: "javascript" } }); expect(form.queryByText(/Channel name already exists/i)).toBeTruthy(); }); test("It should disable the submit button", () => { const form = render( <ChannelCreator channels={["javascript", "python", "php7"]} username={username} /> ); const input = form.getByLabelText("Name"); fireEvent.change(input, { target: { value: "javascript" } }); expect(form.getByText("Create Channel").disabled).toBeTruthy(); }); }); describe("When a user clicks create channel button", () => { beforeEach(() => { global.fetch = jest.fn( () => new Promise((resolve, reject) => { resolve({ statusCode: 201, json() { return { statusCode: 201 }; } }); }) ); }); test("It should display a spinner until response received", async () => { const form = render( <ChannelCreator channels={["javascript", "python", "php7"]} username={username} /> ); const button = form.getByText("Create Channel"); // Click the channel create button fireEvent.click(button); // Wait for the element to change to a spinner const spinner = await waitForElement(() => form.getByTestId("spinner")); // test to see if spinner exists expect(spinner).toBeTruthy(); }); test("It should clear the input field", async () => { const form = render( <ChannelCreator channels={["javascript", "python", "php7"]} username={username} /> ); const button = form.getByText("Create Channel"); const input = form.getByLabelText("Name"); // Click the channel create button fireEvent.change(input, { target: { value: "ninjas" } }); // checks to see if input value is set to ninjas expect(input.value).toBe("ninjas"); fireEvent.click(button); // wait for setState to update input value to "" await waitForElement(() => input.value === ""); // checks to see if spinner is removed expect(form.queryByTestId("spinner")).toBeFalsy(); // checks to see if input field is cleared expect(input.value).toBe(""); }); test("It should close the channel form", async () => { const form = render( <ChannelCreator channels={["javascript", "python", "php7"]} username={username} /> ); const button = form.getByText("Create Channel"); const input = form.getByLabelText("Name"); // Click the channel create button fireEvent.change(input, { target: { value: "ninjas" } }); // checks to see if input value is set to ninjas expect(input.value).toBe("ninjas"); fireEvent.click(button); // wait for setState to update input value to "" await waitForElement(() => form.queryByText("Create Channel") === null); expect(form.queryByText("Create Channel")).toBeNull(); }); });
import React, { useState, useEffect } from 'react' import axios from "axios"; const Upload = () => { const [tag, setTag] = useState(""); const [title, setTitle] = useState(""); const [file, setFile] = useState(); const auth = { headers: { token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjYwZDk2MzllODg2ODQ2MmEyNDQ1ZWFmYSIsInJvbGUiOiJzdGFmZiIsImlhdCI6MTYyNDg3NDEwNH0.5SqvAPYQ9jT_nqynuYCxMYT5vYXFMNeWJb6PaNR_I40" } } const handelSubmit = (e) => { e.preventDefault(); const formData = new FormData(); formData.append("tag", tag) formData.append("title", title) formData.append("file", file) // const formData = { tag, title, file }; axios.post("http://localhost:8080/contents/upload/60dc8be6a091403cf83921ec", formData, auth) .then((res) => console.log(res.data)) .catch((err) => console.log(err.response.data)); // setTag("") // setTitle("") // setFile() }; return ( <div className="container"> <form onSubmit={handelSubmit} encType="multipart/form-data"> <div> <label className="form-label" htmlFor="tag"> tag </label> <input className="form-control" type="text" id="tag" value={tag} onChange={(event) => setTag(event.target.value)} ></input> </div> <div> <label className="form-label" htmlFor="title"> title </label> <input className="form-control" type="text" id="title" value={title} onChange={(event) => setTitle(event.target.value)} ></input> </div> <div> <label className="form-label" htmlFor="file"> file </label> <input className="form-control" type="file" id="file" name="file" onChange={(event) => setFile(event.target.files[0])} ></input> </div> <button type="submit" className="btn btn-primary mt-3"> Submit </button> </form> </div> ) } export default Upload
(function () { 'use strict'; /** * @ngdoc service * @name teachers.factory:Teachers * * @description * */ angular .module('teachers') .factory('Teachers', Teachers); function Teachers($http, consts) { var TeachersBase = {}; TeachersBase.someValue = 'Teachers'; TeachersBase.getTeachersData = function () { return $http({ method: "GET", url: consts.serverUrl + "Website/GetTeachersData", params: {loginToken: localStorage.getItem("loginToken")} }); }; TeachersBase.likePoster = function(posterId){ return $http({ method: "GET", url: consts.serverUrl + "Website/LikePoster", params: {posterId:posterId, loginToken: localStorage.getItem("loginToken")} }); } TeachersBase.likePlan = function(lessonPlanId){ return $http({ method: "GET", url: consts.serverUrl + "Website/LikeLessonPlan", params: {lessonPlanId:lessonPlanId, loginToken: localStorage.getItem("loginToken")} }); } return TeachersBase; } }());
import React, { Component, PropTypes } from 'react' import PageTitle, { PreHeading } from './PageTitle' import { Tiles, Tile } from './Tiles' import Repo, { where } from '../Repo' import { nextStep } from '../utils/whereToGo' import { Link } from 'react-router' import { whereToGoInCategory } from '../utils/whereToGo' import { connect } from 'react-redux' import Term from './Term' import { categoryProgress } from '../reducers/progress' import ShareButton from './ShareButton' import { pushState } from 'redux-router' import { resetProgress } from '../actions' import '../scss/CategoryDone.scss' import '../scss/ResetButton.scss' @connect(state => ({ type: state.router.params.type, progress: state.progress }), dispatch => ({ dispatch, pushState })) export default class CategoryDone extends Component { static propTypes = { type: PropTypes.string.isRequired, progress: PropTypes.object.isRequired, dispatch: PropTypes.func, pushState: PropTypes.func } constructor (props) { super(props) this.state = { category: where({ type: props.type }) } } reset () { const { dispatch, pushState } = this.props dispatch(resetProgress()) dispatch(pushState(null, '/')) } render () { const { progress } = this.props const { category } = this.state const nextCategory = nextStep(progress).category const rest = Repo.categories .filter(c => c.id !== nextCategory.id) .sort((a, b) => { return categoryProgress(a, progress).percent - categoryProgress(b, progress).percent }) const categoryTileWithProgress = (progress, cls) => category => { const to = whereToGoInCategory(progress, category) return <Link key={category.id} to={to}> <Tile category={category} progress={progress} type={cls} /> </Link> } return ( <div className='CategoryDone'> <PageTitle type='small centered shadow'> <h1>Godt gået!</h1> <PreHeading>Nu er du (næsten) ekspert indenfor &hellip;</PreHeading> </PageTitle> <ul className='CategoryDone-terms'> {category.terms.map(term => <Term key={term}>{term}</Term>)} </ul> <ShareButton type='facebook'>Fortæl dine venner</ShareButton> <div className='CategoryDone-next'>Næste<br />udfordring</div> <div className='CategoryDone-nextCategory'> {categoryTileWithProgress(progress)(nextCategory)} </div> <Tiles> {rest.map(categoryTileWithProgress(progress, 'small'))} </Tiles> <div className='ResetButton'> <a href='' onClick={this.reset.bind(this)}><i></i>Start forfra</a> </div> </div> ) } }
#pragma strict // var touchString; var isOuter:boolean; var number:int; function Start () { // Debug.Log("Ring Script called"); // touchString = "I am touched"; } function Update () { }
(function(shoptet) { /** * * @param {String} url * url = url of AJAX request * @param {String} type * type = type of request, get or post * @param {Object} data * data = serialized form data in case of post request, empty string in case of get request * @param {Object} callbacks * callbacks = object with functions to be fired after request * @param {Object} header * header = identification of request, only for internal use */ function makeAjaxRequest(url, type, data, callbacks, header) { return new Promise(function(resolve, reject) { // TODO: remove this control after the IE browser will be completely unsupported // and use default parameter (callbacks = {}) if (typeof callbacks === 'undefined') { callbacks = {} } var xmlhttp = new XMLHttpRequest(); xmlhttp.open(type, url, true); if (header && header.hasOwnProperty('X-Shoptet-XHR')) { if (header['X-Shoptet-XHR'] === 'Shoptet_Coo7ai') { xmlhttp.setRequestHeader('X-Shoptet-XHR', 'Shoptet_Coo7ai'); } } xmlhttp.setRequestHeader("X-Requested-With", "XMLHttpRequest"); if(header && header.hasOwnProperty('Content-Type')) { xmlhttp.setRequestHeader('Content-Type', header['Content-Type']); } else if (type === shoptet.ajax.requestTypes.post) { xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } xmlhttp.onload = function() { if (xmlhttp.status >= 200 && xmlhttp.status < 300) { var response = new shoptet.ajax.AjaxResponse(xmlhttp.response); var allowedCallbacks = [ 'success', 'failed', 'redirect', 'complete' ]; allowedCallbacks.forEach(function(callback) { response.setCallback(callback, function() { if (callbacks.hasOwnProperty(callback) && typeof callbacks[callback] === 'function' ) { callbacks[callback](response); } }); }); response.processResult(); // TODO: postpone the notification in the case of the requests chaining, // TODO: for example in the cart between the initial action and the final // TODO: loading of the actual cart. response.showNotification(); resolve(response); } else { reject( { status: this.status, statusText: this.statusText } ); } } xmlhttp.onerror = function() { reject({ status: this.status, statusText: this.statusText }); }; xmlhttp.send(shoptet.common.serializeData(data)); }); } shoptet.ajax = shoptet.ajax || {}; shoptet.ajax.makeAjaxRequest = makeAjaxRequest; shoptet.ajax.requestTypes = { get: "GET", post: "POST" }; shoptet.ajax.pendingClass = 'ajax-pending-element'; })(shoptet);
import React from 'react' const CommentsList = ({comments}) => { return( <> <h3> Comments: </h3> {comments && comments.map((comment, key) => ( <div className='comment' key={key}> <h4> {comment.username} </h4> <p> {comment.text} </p> </div> ))} </> ) } export default CommentsList
/* * Module de gestion du stockage en session */ export function checkToken() { return sessionStorage.getItem('token'); } export function checkTokenLogin() { if (sessionStorage.getItem('token')) { document.location.href="./index.html"; } }
import React from 'react'; import { mount } from 'enzyme'; import { ComicsNav } from './ComicsNav'; import 'jest-styled-components'; describe('ComicsNav', () => { let getComics; beforeEach(() => { getComics = jest.fn(); }); it('should render without crashing', () => { const wrapper = mount(<ComicsNav {...{ getComics }} />); expect(wrapper).toHaveLength(1); }); it('should render the correct JSX', () => { const wrapper = mount(<ComicsNav {...{ getComics }} />); expect(wrapper).toMatchSnapshot(); }); });
import React from "react"; import Bar from "../assets/img/bar.jpg"; var bar = { width: "90%", height: "auto" }; function Home(){ return ( <div className="container"> <div className="welcome"> <h4>Thanks for coming!</h4> </div> <div className="bar"> <img style={bar} src={Bar} alt=""/> </div> </div> ); } export default Home;
export default function() { return [ {title:"Javascript: The Good Parts", pages : 101}, {title:"Harry Potter", pages : 1}, {title:"The Dark Tower", pages : 12}, {title:"Eloquent Ruby", pages : 1013} ] }
'use strict'; describe('Controller: MainCtrl', function () { beforeEach(module('myApp')); var SplashPagesCtrlShow, locationFactory, SplashPagesCtrl, splashFactory, scope, $location, $httpBackend, deferred, q, store = {}; beforeEach(module('myApp', function($provide) { locationFactory = { get: function () { deferred = q.defer(); return {$promise: deferred.promise}; } }, splashFactory = { update: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, query: function () { deferred = q.defer(); return {$promise: deferred.promise}; }, get: function () { deferred = q.defer(); return {$promise: deferred.promise}; } } $provide.value("Location", locationFactory); $provide.value("SplashPage", splashFactory); })); describe('Controller: Show', function () { beforeEach(inject(function (_$httpBackend_, $controller, $rootScope, _$location_, $q) { $httpBackend = _$httpBackend_; q = $q; scope = $rootScope.$new(); $location = _$location_; SplashPagesCtrl = $controller('SplashPagesCtrlShow', { $scope: scope, }); })); it('should get the location and the splash_page, why not', function () { spyOn(locationFactory, 'get').andCallThrough(); spyOn(splashFactory, 'query').andCallThrough(); expect(scope.loading).toBe(true); var location = { location_name: "simon"} var splash_page = { splash_page: { splash_page_name: 'lobby'}, access_types: [{ name: "password"}]} deferred.resolve(location) scope.$apply() expect(scope.location).toBe(location) }); }); describe('Controller: NewCtrl', function () { beforeEach(inject(function (_$httpBackend_, $controller, $rootScope, _$location_, $q) { $httpBackend = _$httpBackend_; q = $q; scope = $rootScope.$new(); $location = _$location_; SplashPagesCtrl = $controller('SplashPagesCtrlNew', { $scope: scope, }); })); it('should get the location and all the splash_pages, why not', function () { spyOn(locationFactory, 'get').andCallThrough(); spyOn(splashFactory, 'get').andCallThrough(); expect(scope.loading).toBe(true); var location = { location_name: "simon"} var splash_page = { splash_page_name: 'Lobby' } deferred.resolve(location) scope.$apply() expect(scope.location).toBe(location) }); }); });
/** export d3scomos **/ if (typeof define === 'function' && define.amd) { define("d3scomos", ["d3"], function () { return d3scomos; }); } else if ('undefined' !== typeof exports && 'undefined' !== typeof module) { module.exports = d3scomos; } else { window.d3scomos = d3scomos; } })(window);
import React from "react"; import styled from "styled-components"; import { ModalHeader, ModalBody } from "reactstrap"; import { Modal } from "../../../common"; import { Link } from "react-router-dom"; const StyledModal = styled(Modal)` && { max-width: 620px; width: 100%; margin: 0 auto; padding: 15px; .modal-content { box-shadow: 5px 5px 95px rgba(0, 0, 0, 0.5); border-radius: 6px; border: none; } .modal-header { background: #ffffff; border-bottom: none; padding: 5px 20px 0; .close { opacity: 1; span { color: #6254e8; font-size: 45px; font-weight: 400; } } } .modal-body { padding: 15px 40px 75px; text-align: center; h4 { color: #08135a; font-size: 30px; margin: 10px 0; line-height: 32px; } .modal__text { color: #08135a; font-size: 18px; line-height: 28px; margin: 0 auto; font-weight: 500; a { color: #6254e8; transition: 0.3s ease; &:hover { color: #f6732f; } } } } @media only screen and (max-width: 600px) { .modal-body { .modal__text { font-size: 16px; } h4 { font-size: 26px; line-height: 30px; } } } @media only screen and (max-width: 535px) { .modal-body { padding: 0 20px 40px; .modal__text { font-size: 15px; line-height: 20px; } h4 { font-size: 22px; } } } } `; const ModalStripeWrong = ({ isOpen, handleToggle }) => { return ( <StyledModal isOpen={isOpen} toggle={handleToggle} wrapClassName="wrap-modalDashboard" id="modal-zoom" centered > <ModalHeader toggle={handleToggle}></ModalHeader> <ModalBody> <h4>Something went wrong</h4> <div className="modal__text"> Sorry, something went wrong while trying to set your payment methods. <br /> Please try again or contact us <Link to="/contact-us">here</Link> </div> </ModalBody> </StyledModal> ); }; export default ModalStripeWrong;
'use strict'; const widget = require('..'); describe('@pk/widget', () => { it('needs tests'); });
const express = require('express'); const path = require('path'); const bodyParser = require('body-parser'); const session = require('express-session'); const morgan = require('morgan'); const addRequestId = require('express-request-id')(); const MongoStore = require('connect-mongo')(session); const cors = require('cors'); const logger = require('./src/config/winston'); const db = require('./db'); const config = require('./src/config/config'); const router = require('./src/routes'); const app = express(); const { PORT } = config; const whitelist = [ config.FRONT_ORIGIN_LOCAL, config.FRONT_ORIGIN_REMOTE, `http://localhost:${PORT}`, 'http://localhost:8080', ]; app.use(cors({ credentials: true, origin(origin, callback) { if (origin === undefined || whitelist.indexOf(origin) !== -1) { callback(null, true); } else { logger.warn(`"${origin}" is not allowed by CORS`); callback(new Error('Not allowed by CORS')); } }, })); // X-Request-Id header app.use(addRequestId); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); if (config.IS_PRODUCTION) { app.set('trust proxy', 1); } app.use( session({ secret: config.SESSION_SECRET, resave: true, cookie: { secure: config.IS_PRODUCTION, httpOnly: true, sameSite: 'none', maxAge: 60 * 60 * 24 * 1000, }, saveUninitialized: false, store: new MongoStore({ mongooseConnection: db, }), }), ); // logging morgan.token('request-body', (req, res) => { const body = Object.assign({}, req.body); // is not safe to leave unsecure user's passwords in logs if ('password' in body) { body.password = '***'; } return JSON.stringify(body); }); morgan.token('request-id', (req, res) => req.id); morgan.token('user', (req, res) => { if (req.session.userId) return req.session.userId; return 'no user'; }); const loggerFormat = '[req_id: :request-id][uid: :user] [:status] :remote-addr :method :url :response-time ms - :res[content-length] \n body :request-body'; app.use(morgan(loggerFormat, { skip(req, res) { return res.statusCode < 400; }, stream: logger.stream, })); app.use(morgan(loggerFormat, { skip(req, res) { return res.statusCode >= 400; }, stream: logger.stream, })); // routes app.use(router); // set files folder if (config.IS_PRODUCTION) { logger.info('Worker is running in PRODUCTION mode...'); app.use('/app/uploads', express.static(path.join(__dirname, 'uploads'))); } else { logger.info('Worker is running in DEV mode...'); app.use('/uploads', express.static(path.join(__dirname, 'uploads'))); } app.listen(PORT, () => { logger.info(`${process.pid} [pid]: Server is listening on the port ${PORT}`); });
import React, { Fragment } from 'react' export const Debug = ({ children, log }) => { if (log) { console.log(children) } return ( <pre style={{ maxHeight: '400px', backgroundColor: '#fafafa', padding: '20px', overflowX: 'scroll', whiteSpace: 'pre-wrap' }} children={JSON.stringify(children, null, 2)} /> ) } export const withDebug = Component => props => { console.log(props) return <Component {...props} /> }
import React from 'react' import { Route, Redirect, } from 'react-router-dom' // 登录状态 const isLogin = true // ...rest es6 rest参数 // Route Component 接收route props const ProtectedRoute = ({component: Component, ...rest}) => { // 内联渲染 // Route render, render接收传入函数 return (<Route {...rest} render={(props) => ( // 根据【是否登录】判断默认路由 // 否:goto登录页,并且记录当前location // 是:Route Component匹配的路由 !!isLogin ? <Component {...props} /> : <Redirect to={{ pathname: '/login', state: {from: props.location} }}/> )}/>) } export default ProtectedRoute
require('dotenv').config(); const UserModel = require('../model/user'); const jwt = require('jsonwebtoken'); const { mongoDB } = require('../error/mongoDB'); const student = require('../model/student'); const Employee = require('../model/employee'); const config = require('config'); const Batch = require('../model/batch'); //! base API exports.signup = async (req, res) => { try { let body = req.body; let userData; if (body.userType === 'Student') { userData = await createStudent(body, req); } if (body.userType === 'Employee') { const employee = Employee(body.employee); body.employee = employee; userData = new UserModel(body); await Promise.all([employee.save(), userData.save()]); } userData.salt = undefined; userData.hashed_password = undefined; return res.status(201).json({ msg: "user Created", data: userData }); } catch (error) { console.log(error); const errorMsg = mongoDB(error); if (errorMsg.length) { return res.status(403).json({ error: errorMsg[0], errorMsgs: errorMsg }); } return res.status(500).json({ error: "Error Occured" }); } } exports.signin = async (req, res) => { try { const { email, password } = req.body; let userData = await UserModel .findOne({ email: email }) .populate({ path: "student" }).populate('employee'); if (!userData) { return res.status(400).json({ error: "User not found" }); } if (!userData.authenticate(password)) { return res.status(401).json({ error: "Email and Password dont match" }); } const username = { id: userData._id }; const acessToken = jwt.sign(username, process.env.ACESS_TOKEN_SECRET); userData.hashed_password = undefined; userData.salt = undefined; return res.json({ sucess: true, data: { acesstoken: acessToken, user: userData } }); } catch (error) { return res.status(500).json({ error: "Autheticate Error" }); } } // ! middlewares exports.jwtAuthVerification = async (req, res, next) => { const authHeader = req.headers.authorization; const token = authHeader && authHeader.split(' ')[1]; if (token == null) return res.status(401).json({ status: false, error: "This is user is not Authorized" }); jwt.verify(token, process.env.ACESS_TOKEN_SECRET, async (err, username) => { try { if (err) return res.status(401).json({ status: false, error: "This is user is not Authorized" }); const userData = await UserModel.findOne({ _id: username.id }); if (!userData) return res.status(401).json({ status: false, error: "This is user is not Authorized" }); req.user = userData; next(); } catch (error) { console.log(error); return res.json({ error: "Error Occured" }); } }); } async function createStudent(body, req) { try { const studentData = student(body.student); body.student = studentData; const userData = new UserModel(body); if (studentData.program.length) { // * calculating ending date const programData = req.program; let startingYear = new Date(body.student.startingBatch); startingYear.setMonth(startingYear.getMonth() + (12 * programData.duration)); startingYear.setMonth(startingYear.getMonth() - 2); studentData.endingbatch = new Date(startingYear); let batchData = await Batch.findOne({ program: programData._id, startingDate : studentData.startingBatch }); if (!batchData) { batchData = await Batch({ startingDate: studentData.startingBatch, endingDate: studentData.endingbatch, program: programData._id, }); studentData.batch = batchData; await Promise.all([studentData.save(), userData.save(), batchData.save()]); return userData; } studentData.batch = batchData; } await Promise.all([studentData.save(), userData.save()]); return userData } catch (error) { throw error; } }
/* global View */ /* eslint-disable no-unused-vars */ 'use strict'; class Repository extends View { constructor(data) { super(); this._data = data; } render() { const ulInfo = document.getElementById('info'); ulInfo.innerHTML = ''; this.createAndAppend('li', ulInfo, { html: 'Name : ' + "<a href=" + this._data.html_url + ' target="_blank" >' + this._data.name + "</a>", }); this.createAndAppend('li', ulInfo, { html: 'Description : ' + '<span>' + this._data.description + '</span>' }); this.createAndAppend('li', ulInfo, { html: 'Forks : ' + '<span>' + this._data.forks + '</span>' }); this.createAndAppend('li', ulInfo, { html: 'Updated : ' + '<span>' + this._data.updated_at + '</span>' }); } fetchContributors() { return this.fetchJSON(this._data.contributors_url); } }
const { ApolloServer } = require("apollo-server-express"); const typeDefs = require("./schema"); const resolvers = require("./resolvers"); const dataSources = require("./datasources"); const context = async ({ req }) => { return { isAuth: req.isAuth, }; }; const apolloServer = new ApolloServer({ typeDefs, resolvers, dataSources, context, introspection: true, playground: true, }); module.exports = apolloServer;
{ "template" : "email/wm-ringmail-email-campaign01/parachute/parachute.html" }
import updateAttribute from './updateAttribute'; import updateNode from './updateNode'; import { applyHandlers } from './mountHandlerQueue'; export default function updater (parts, values, oldValues = [], context, root) { for (let i = 0, ln = parts.length; i < ln; i++) { const part = parts[i]; const value = values[i]; const oldValue = oldValues[i]; const { isAttribute, isNode } = part; if (isAttribute) { Object.entries(value).forEach(([attrName, attrValue]) => { const oldAttrValue = oldValue && oldValue[attrName]; updateAttribute(part, attrName, attrValue, oldAttrValue); }); } else if (isNode) { updateNode(part, value, oldValue, context); } } /** * if the node is the root of the mount * call the mount/update handlers once dom nodes are attached */ if (root) { applyHandlers(); } }
import React, {Fragment, Component} from "react"; import {Col, Divider, Input, Row} from "antd"; class TableSearch extends Component { state = { name: "", inputValues: { name: "", phone: "", } } change(e, name) { this.setState(()=>{ const inputValues = this.state.inputValues; console.log(e.target) inputValues.name = e.target.value return{ inputValues:inputValues } }) } render() { // const { data, pagination, loading } = this.state; return ( <Fragment> <Row gutter={16}> <Col className="gutter-row" span={6}> <Row gutter={16} justify="space-around" align="middle"> <Col span={5}> <div>姓名</div> </Col> <Col span={19}> <Input placeholder="Basic usage"/> </Col> </Row> </Col> <Col className="gutter-row" span={6}> <Row gutter={16} justify="space-around" align="middle"> <Col span={5}> <div>电话</div> </Col> <Col span={19}> <Input placeholder="Basic usage" value={this.state.inputValues.name} onChange={(e) => this.change(e, "name")}/> </Col> </Row> </Col> <Col className="gutter-row" span={6}> <div>col-6</div> </Col> <Col className="gutter-row" span={6}> <div>col-6</div> </Col> </Row> </Fragment> ) } } export default TableSearch
export default { authRequest: "AUTH_REQUEST", logInResponse: "LOG_IN_RESPONSE", logOutResponse: "LOG_OUT_RESPONSE", checkResponse: "AUTH_CHECK_RESPONSE" };
// Dependencies const express = require("express"); const morgan = require("morgan"); const mongoose = require("mongoose"); // Setting up Express const PORT = process.env.PORT || 3000; const app = express(); // Setting up Morgan, which is a logger app.use(morgan("dev")); // Setting up express app to handle data parsing app.use(express.urlencoded({ extended:true })); app.use(express.json()); app.use(express.static("public")); // Setting up Mongo DB for heroku and localhost let MONGODB_URI = process.env.MONGODB_URI || "mongodb://localhost/workout"; mongoose.connect(MONGODB_URI, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false }); // Creating Routes require("./routes/apiRoutes")(app); require("./routes/htmlRoutes")(app); // Starts server to begin listening app.listen(PORT, () => { console.log(`App listening on port ${PORT}.`) });
import React from 'react'; import Events from './materialui/Events'; const Aside = () => { return ( <div className="aside"> <Events/> </div> ); }; export default Aside;
var myData; var balls = []; //var myImg //var myImg2 var mic var myImg0 function preload() { //myImg= loadImage("./assets/candle1.png"); //myImg2= loadImage("./assets/candle2.png"); myImg0= loadImage("./assets/candles.png"); } function setup() { createCanvas(windowWidth, windowHeight); mic = new p5.AudioIn() mic.start() for (var i = 0; i < windowWidth*4; i++) { var newBall = new Ball(random(3, 5)); balls.push(newBall); } } function draw() { background(168, 200, 255); fill(255) for (var i = 0; i < balls.length; i++) { var ball = balls[i]; ball.move(); ball.display(); } //image(myImg,windowWidth/2-windowHeight/24,windowHeight/2-windowHeight/4,windowHeight/12,windowHeight/2); if(windowHeight<windowWidth) {image(myImg0,windowWidth/2-windowHeight/2,0,windowHeight,windowHeight) } else{image(myImg0,0,windowHeight/2-windowWidth/2,windowWidth,windowWidth)} var p1 if( windowWidth>windowHeight){ p1=windowHeight/4} else{ p1=(windowHeight-windowWidth)/2+windowWidth/4 } var vol = mic.getLevel() fill(255, 209, 7,90) //1 swieczka var remap0 = map(vol,0,1,2,200) var remap = map(vol,0,1,2,500) var remap1 = map(vol,0,1,2,1000) fill(255, 119, 0) ellipse(windowWidth/2,p1,remap0) fill(255, 220, 71,99) ellipse(windowWidth/2,p1,remap) fill(255, 232, 137,90) ellipse(windowWidth/2,p1,remap1) //2 2 swwieczka //strokeWeight(10) //fill('red') //if (windowHeight<windowWidth) { /// fill(255, 119, 0) //ellipse(windowWidth/2,p1,remap0) //fill(255, 220, 71,99) //ellipse(windowWidth/2,p1,remap) //fill(255, 232, 137,90) //ellipse(windowWidth/2,p1,remap1) //ellipse((windowWidth-windowHeight)/2+windowHeight/4,windowHeight*15/40,10,10) //} else{ellipse(windowWidth/4,(windowHeight-windowWidth)/2+windowWidth*15/40,10,10)} } function Ball(radius) { noStroke() this.radius = radius; this.x = random(this.radius, windowWidth*5 - this.radius); this.y = random(this.radius, windowHeight*5 - this.radius); this.incrementX = random(-1,1); this.incrementY = random(-1,1); this.display = function() { ellipse(this.x, this.y, this.radius * 2); } this.move = function() { this.x += this.incrementX; this.y += this.incrementY; //var p = 400 if (this.x > windowWidth*5 - this.radius || this.x < this.radius) { this.incrementX *= -1 // print(this.x); // print(this.radius); } if (this.y > windowHeight*5 - this.radius || this.y < this.radius) { this.incrementY *= -1 // print(this.y); // print(this.radius); } } } function windowResized() { resizeCanvas(windowWidth, windowHeight); }
// import logo from './logo.svg'; // import './App.css'; import Hello from './component/Hello'; // 내가 만든 컴포넌트를 쉽게 사용하려면 import Hello 해야한다. function App() { return ( // 브라우저가 해석해야하는 부분 (JSX 문법) // 반드시 root element는 있어야 한다. <div className="App"> <Hello /> </div> ); } export default App; // export를 해야 다른 데에서 import를 할 수 ㅇㅆ다.
import React, { Component } from 'react'; import _ from 'lodash'; const formConfig={ fields:[ { rowId: 1, col: 8, orderNum:1, label: '业务名称', showLabel: true, key:'serviceName', type: 'input', props: { placeholder: '请输入业务关键字', defaultValue: '' }, needExpend: false, formItemLayout: { labelCol: { xs: { span: 24 }, sm: { span: 6 }, }, wrapperCol: { xs: { span: 24 }, sm: { span: 18 }, } } } ] } export {formConfig}
import { useStore } from "context"; import { LOAD_COUNTRIES, SEARCH_COUNTRIES, FILTER_COUNTRIES_BY_REGION, SELECT_COUNTRY, CHANGE_PAGE, } from "./types"; export const useDispatch = () => { const { dispatch } = useStore(); return dispatch; }; export const loadCountries = (countries) => ({ type: LOAD_COUNTRIES, countries, }); export const searchCountries = (searchKeyword) => ({ type: SEARCH_COUNTRIES, searchKeyword, }); export const filterCountriesByRegion = (region) => ({ type: FILTER_COUNTRIES_BY_REGION, region, }); export const selectCountry = (country) => ({ type: SELECT_COUNTRY, country, }); export const changePage = (page) => ({ type: CHANGE_PAGE, page, });
/** * Created by cl-macmini-63 on 1/16/17. */ 'use strict'; const userModel = require( 'model/user.js' ); const Boom = require('boom'); const log = require('Utils/logger.js'); const logger = log.getLogger(); const commonFunction=require('Utils/commonfunction.js') const messenger=require('Utils/messenger') const responseFormatter = require('Utils/responseformatter'); var async=require('async') var config=require('config') module.exports={}; module.exports.createNewUser = function(request, reply){ var payload = request.payload; console.log('payload :: ',payload); userModel.createNewUser(payload, function(response){ console.log("In Controller user returned by create:", response); //try{ // if (response === null || response === undefined){ // reply(Boom.badImplementation("User could not be created")); // } // else{ // //logger.debug("user returned by create:", user); // if (response.status == 'success'){ // reply({statusCode:200, message: "created successFully", data: response || null}); // } // else{ // // if (response.error_type == 'validation_error'){ // responseFormatter.formatServiceResponse(response.data,reply); // } // else{ // reply(response); // } // } // } //} //catch(e){ // logger.error("Error creating user: " + e.message); // reply(Boom.badImplementation(e.message)); //} //if(response.status == 'success'){ // reply(response); //} ////responseFormatter.formatServiceResponse(response, reply,'OTP sent Successfully on your phone', 'success',200); //else{ // console.log('error in sendOTP'); // reply(response); // //responseFormatter.formatServiceResponse('', reply,'Error occured. Otp sending failed.', 'error'); //} reply(response) }); }; module.exports.getUser = function(request, reply){ logger.debug('Calling getUser'); logger.debug('request.params.userid',request.params.user_id); userModel.getUserById(request.params.user_id, request.auth.credentials, function(response){ console.log('Response Get User:', response); try{ //if not data, implies user not found if (response.data == null || response.data == undefined || response.data == ''){ reply(Boom.notFound("User not found")); } else{ reply(response); } } catch(e){ logger.error('Error finding user: ', e.message); reply(Boom.notFound(e.message)); } } ); }; module.exports.createUserHandler=function(request,reply){ const payloadData=request.payload userModel.createUserModel(payloadData,function(err,data){ if(err){ console.log('error',err); reply(err) } else{ console.log("data___",data) //responseFormatter.formatServiceResponse({}, reply, err.message,'success',err.statusCode); responseFormatter.formatServiceResponse({}, data, 'User Registered SuccessFully','Success',data.statusCode); } }) } //module.exports.forgotPasswordUser = function (payloadData, callback) { // let emailData=null // var resetToken=commonFunction.generateRandomStringBigger() // var passwordUpdated=null // async.series([ // //Check Whether Atleast one field entered // function(cb){ // const criteria={ // email:payloadData.email // } // const options={ // lean:true // } // userModel.getUser(criteria,{},options,function(err,data){ // if(err){ // cb(err) // } // else{ // console.log(!data) // if(!data){ // cb(config.messages.errors.notFound.EMAIL_NOT_REGISTERED) // } // else{ // emailData=data // console.log("emailData",emailData) // cb(null) // } // } // }) // }, // function(cb){ // const criteria={ // email:payloadData.email // } // const dataToUpdate={ // passwordResetToken:resetToken // } // const options={ // lean:true, // new:true // } // userModel.updateUser(criteria,dataToUpdate,options,function(err,data){ // if(err){ // cb(err) // } // else{ // passwordUpdated=data // cb(null) // } // }) // }, // function (cb) { // if (emailData) { // const smsDetails = { // user_name: emailData.first_name, // password_reset_token:resetToken, // password_reset_link: 'http://localhost:3001/'+ ' ' + '/passwordResetToken=' + resetToken + '&email=' + payloadData.email // } // // Email To Be Sent // const message="<h1> Forgot Password Link </h1> <br/><br/> Hello smsDetails.user_name, <br/> To Rest Password, please click <a href=smsDetails.password_reset_link>here</a>" // messenger.sendMail("chandan.sharma@click-labs.com",emailData.email,"reset link",smsDetails.password_reset_link,function(err,msg){ // if(err){ // cb(err) // } // else{ // console.log("Message",msg) // cb(null) // } // }) // } // else { // cb("Implementation Error") // } // }], // function(err,data){ // if(err){ // callback(err) // } // else{callback(data) // } // }) //} module.exports.getMasterServicesUsers = function(request, reply){ console.log("in handler getMasterServices ::: "); userModel.getMasterServices(function(err,data){ if(err){ reply(err) } else{ responseFormatter.formatServiceResponse(data,reply, 'Fetched successfully','success',200); } }); }; module.exports.getGigsHandler = function(request, reply){ console.log("in handler getMasterServices ::: "); const payload=request.query userModel.getGigsServices(payload,function(err,data){ if(err){ reply(err); } else{ responseFormatter.formatServiceResponse(data,reply, 'Fetched successfully','success',200); } }); }; module.exports.updateUserProfile = function(request, reply){ //logger.debug('Updating user: ', request.payload); var payload = request.payload; console.log('payload updateUserProfile :::: ',payload); try{ //same requester so proceed with update userModel.updateUserProfile(payload, function(response){ if(response.status == 'success'){ reply(response); } else{ console.log('error in updateUserProfile ',response); reply(response); } } ); } catch(err){ logger.error('In Catch Update failed', err); reply(Boom.badImplementation('Access denied')); return; } }; module.exports.updateUserHandler = function(request, reply){ //logger.debug('Updating user: ', request.payload); var payload = request.payload; console.log('payload updateUserProfile :::: ',payload); try{ //same requester so proceed with update userModel.updateUserHandler(payload, function(response){ if(response.status == 'success'){ reply(response); } else{ console.log('error in updateUserProfile ',response); reply(response); } } ); } catch(err){ logger.error('In Catch Update failed', err); reply(Boom.badImplementation('Access denied')); return; } }; module.exports.getUserProfile=function(request,reply){ let payload=request.query userModel.getUserProfileModel(payload,function(err,data){ if(err){ reply(err) } else{ responseFormatter.formatServiceResponse(data, reply, 'userProfile Data','Success',200); } }) } module.exports.forgotPasswordHandler=function (request, reply) { const payloadData = request.payload; userModel.forgotPasswordUser(payloadData, function (err,data) { if (err) { reply(err); } else { responseFormatter.formatServiceResponse(data, reply, "Reset Password Link has been sent to email" , "success",200); } }); } module.exports.userFavourite=function(request,reply){ let payload=request.payload userModel.userFavouriteModel(payload,function(err,data){ if(err){ reply(err) } else{ responseFormatter.formatServiceResponse(data,reply, config.constants.messages.Success.insertion,'success',200); } }) } module.exports.removeFavouriteService=function(request,reply){ let payload=request.payload userModel.removeFavouriteService(payload,function(err,data){ if(err){ reply(err) } else{ responseFormatter.formatServiceResponse(data,reply, config.constants.messages.Success.updation,'success',200); } }) } module.exports.removeFavouriteGig=function(request,reply){ let payload=request.payload userModel.removeFavouriteGig(payload,function(err,data){ if(err){ reply(err) } else{ responseFormatter.formatServiceResponse(data,reply, config.constants.messages.Success.updation,'success',200); } }) } module.exports.getUserFavourite=function(request,reply){ let payload=request.query userModel.getUserFavouriteModel(payload,function(err,data){ if(err){ reply(err) } else{ responseFormatter.formatServiceResponse(data,reply, config.constants.messages.Success.insertion,'success',200); } }) } module.exports.resetPasswordUser=function(request,reply){ const payload=request.payload userModel.resetPasswordUser(payload, function (err) { if (err) { reply(err); } else { responseFormatter.formatServiceResponse({}, reply, "Password reset Successfully" , "success",200); } }); } module.exports.changePasswordUser = function(request,reply){ const payload=request.payload userModel.changePasswordUser(payload, function (err) { if (err) { reply(err); } else { responseFormatter.formatServiceResponse({}, reply, "Password changed Successfully" , "success",200); } }); } module.exports.addOrganizationData = function(request, reply){ let user_id = request.auth.credentials.user_id; userModel.addOrganizationData(request.payload ,user_id, function(err,data){ if(err){ reply(err) } else{ responseFormatter.formatServiceResponse(data,reply, 'User Organization Inserted Successfully','success',200); } }); }; module.exports.addBankDetails = function(request, reply){ userModel.addBankDetails(request.payload , function(err,data){ if(err){ reply(err) } else{ responseFormatter.formatServiceResponse(data,reply, 'User Organization Bank Details Inserted Successfully','success',200); } }); }; module.exports.addInsuranceDetails = function(request, reply){ userModel.addInsuranceDetails(request.payload , function(err,data){ if(err){ reply(err) } else{ if(data){ responseFormatter.formatServiceResponse(data,reply, 'User Organization Insurance Details Inserted Successfully','success',200); }else{ responseFormatter.formatServiceResponse(data,reply, 'User Organization Profile not found','error',404); } } }); }; module.exports.toggleNotificationFlag = function(request,reply){ let user_id = request.auth.credentials.user_id; let role = request.auth.credentials.role; let payload = request.payload; console.log('payload in handler toggleNotificationFlag ::: ',payload); userModel.toggleNotificationFlag(user_id ,role , payload, function(data){ console.log('in handler response from toggleNotificationFlag : ',data) reply(data); }); }; module.exports.toggleBGCFlag = function(request,reply){ let payload = request.payload; console.log('payload in handler toggleBGCFlag ::: ',payload); userModel.toggleBGCFlag(payload, function(data){ console.log('in handler response from toggleBGCFlag : ',data) reply(data); }); }; module.exports.getAllPromotions = function(request,reply){ userModel.getAllPromotions(function(err,data){ if(err){ reply(err) } else{ responseFormatter.formatServiceResponse(data, reply, "" , "Success",200) } }) } module.exports.makeFavourites = function(request,reply){ const payload=request.payload userModel.makeFavourites(payload, function (err) { if (err) { reply(err); } else { responseFormatter.formatServiceResponse({}, reply, "Favourites added Successfully" , "success",200); } }); } module.exports.getFavouriteServices = function(request,reply){ let user_id=request.query.user_id; userModel.getFavouriteServices(user_id,function(err,data){ if(err){ reply(err) } else{ responseFormatter.formatServiceResponse(data,reply,'User Favourite services fetched successfully' ,'success',200); } }) } module.exports.getAllFavGigsForSpecificService = function(request,reply){ let user_id = request.auth.credentials.user_id; let service_id = request.params.service_id; console.log('in handler getAllFavGigsForSpecificService ::: '); userModel.getAllFavGigsForSpecificService(service_id , user_id ,function(response){ reply(response); }) }; module.exports.setLanguageParam = function(request,reply){ const payload=request.payload userModel.setLanguageParam(payload, function (err) { if (err) { reply(err); } else { responseFormatter.formatServiceResponse({}, reply, "Language added Successfully" , "success",200); } }); } module.exports.AddOrDeductWalletAmountByUserId = function(request,reply){ let user_id = request.payload.user_id; let amount = request.payload.amount; userModel.AddOrDeductWalletAmountByUserId(request.payload,function(err,data){ if(err){ responseFormatter.formatServiceResponse(err,reply, config.constants.messages.error.dbError,'error',400); } else{ if(data && data.length!=0){ responseFormatter.formatServiceResponse(data,reply, config.constants.messages.Success.get,'success',200); }else{ responseFormatter.formatServiceResponse(data,reply, 'No Details Found','success',200); } } }) } module.exports.getWalletCreditByUserId = function(request,reply){ let user_id = request.query.user_id; console.log('in handler getWalletCreditByUserId ::: '); userModel.getWalletCreditByUserId(user_id ,function(response){ reply(response); }) };
const { Sequelize, DataTypes } = require('sequelize'); const sequelize = require('../sequalize/dbConnection') const sq = sequelize.sequelize; const Sliders = sq.define('Sliders', { tagline: { type: DataTypes.STRING, allowNull: false }, image: { type: DataTypes.STRING, allowNull: false }, description: { type:DataTypes.STRING, allowNull:false } }); // Sliders.sync({alter:true}); module.exports=Sliders;
const express = require('express'); const router = express.Router(); const User = require('../models/user'); const bcrypt = require('bcryptjs'); const passport = require('passport'); const twilio = require('twilio'); // POST ROUTE FOR CHANGING USER'S INFO router.post('/edit/:userID', (req, res, next) => { const userID = req.params.userID; User.findByIdAndUpdate(userID, req.body, {new: true}, (err, theUser) => { if(err) {res.status(400).json(err)} else if(!theUser) {res.status(400).json({message: 'User not found'})} else {res.status(200).json(theUser)} }); }); // ---------------------------------------------------------------------------------- // add orgId to orgs array on user model if provided // also add user to org's users-list if needed // POST ROUTE FOR CREATING A NEW USER router.post('/signup', (req, res, next) => { const email = req.body.email; const password = req.body.password; const firstName = req.body.firstName; const lastName = req.body.lastName; const zipCode = req.body.zipCode; const phoneNumber = req.body.phoneNumber; const orgAdmin = req.body.orgAdmin; if (!email || !password) { res.status(400).json({ message: 'Provide email and password' }); return; } User.findOne({ email }, '_id', (err, foundUser) => { if (foundUser) { res.status(400).json({ message: 'The email already exists' }); return; } const salt = bcrypt.genSaltSync(10); const hashPass = bcrypt.hashSync(password, salt); const theUser = new User({ email, password: hashPass, firstName: firstName, lastName: lastName, zipCode: zipCode, phoneNumber: phoneNumber, orgAdmin: orgAdmin, }); theUser.save((err) => { if (err) { res.status(400).json({ message: 'Something went wrong' }); return; } req.login(theUser, (err) => { if (err) { res.status(500).json({ message: 'Something went wrong' }); return; } res.status(200).json(req.user); }); }); }); }); // ---------------------------------------------------------------------------------- // LOGIN POST ROUTE router.post('/login', (req, res, next) => { passport.authenticate('local', (err, theUser, failureDetails) => { if (err) { res.status(500).json({ message: 'Something went wrong' }); return; } if (!theUser) { res.status(401).json(failureDetails); return; } req.login(theUser, (err) => { if (err) { res.status(500).json({ message: 'Something went wrong' }); return; } // We are now logged in (notice req.user) res.status(200).json(req.user); }); })(req, res, next); }); // ---------------------------------------------------------------------------------- // POST ROUTE FOR LOGOUT router.post('/logout', (req, res, next) => { req.logout(); res.status(200).json({ message: 'Success' }); }); // ---------------------------------------------------------------------------------- // GET ROUTE FOR CHECKING IF USER IS LOGGED IN router.get('/loggedin', (req, res, next) => { if (req.isAuthenticated()) { res.status(200).json(req.user); return; } res.status(403).json({ message: 'Unauthorized' }); }); // ---------------------------------------------------------------------------------- // POST ROUTE FOR DELETING A USER'S ACCOUNT router.post('/delete/:userID', (req, res, next) => { const userID = req.params.userID; User.findByIdAndRemove(userID, (err, theUser) => { if(err) {res.status(400).json(err)} else if(!theUser) {res.status(400).json({message: 'User does not exist'})} else {res.status(200).json({message: 'Success'})} }); }); // ---------------------------------------------------------------------------------- // GET ROUTE FOR PULLING SINGLE USER'S INFO router.get('/:userID', (req, res, next) => { const userID = req.params.userID; User.findById(userID) .populate('events') .populate('organizations') .populate('reviews') .then((theUser) => { if (!theUser) {res.status(400).json({message: 'User does not exist'})} else {res.status(200).json(theUser)} }) .catch((err)=>{ res.status(400).json(err) }); }); // GET ROUTE FOR PULLING ALL USERS router.get('/', (req,res,next)=>{ User.find() .then((allUsers)=>{ if (!allUsers) {res.status(400).json({message: 'User does not exist'})} else {res.status(200).json(allUsers)} }) .catch((err)=>{ res.status(400).json(err); }); }); // ORIGINAL ROUTE FOR SINGLE USER INFO // router.get('/:userID', (req, res, next) => { // const userID = req.params.userID; // User.findById(userID, (err, theUser) => { // if(err) {res.status(400).json(err)} // else if (!theUser) {res.status(400).json({message: 'User does not exist'})} // else {res.status(200).json(theUser)} // }); // }); module.exports = router;
import {pageSize, pageSizeType, paginationConfig, searchConfig} from '../../globalConfig'; import name from '../../dictionary/name'; const filters = [ {key: 'resourceName', title: '资源名称', type: 'text'}, {key: 'resourceType', title: '资源类型', type: 'select', options: [{value: 0, title: 'module'}, {value: 1, title: 'menu'}, {value: 2, title: 'page'}, {value: 3, title: 'action'}]}, {key: 'url', title: 'URL路径', type: 'text'}, {key: 'urlName', title: 'URL名称', type: 'text'}, {key: 'resourceKey', title: '资源代码', type: 'text'}, {key: 'serviceName', title: '服务名', type: 'text'}, {key: 'controllerName', title: '控制层名称', type: 'text'}, ]; const tableCols = [ {key: 'urlName', title: 'URL名称'}, {key: 'url', title: 'URL路径'}, {key: 'serviceName', title: '服务名'}, {key: 'controllerName', title: '控制层名称'}, {key: 'controllerUrl', title: '控制层路径'}, {key: 'requestMode', title: '请求方式', from:'dictionary', position:name.REQUEST_METHOD}, {key: 'resourceName', title: '资源名称'}, {key: 'resourceKey', title: '资源代码'}, {key: 'parentResourceName', title: '上级资源名称'}, {key: 'resourceEnName', title: '资源英文名'}, {key: 'resourceType', title: '资源类型', options: [{value: 0, title: 'module'}, {value: 1, title: 'menu'}, {value: 2, title: 'page'}, {value: 3, title: 'action'}]} ]; const config = { filters, tableCols, pageSize, pageSizeType, paginationConfig, searchConfig, dicNames: [name.REQUEST_METHOD] }; export default config;
import React,{useContext,useState,useEffect} from 'react'; import {Link} from 'react-router-dom'; import AuthService from '../Services/AuthService'; import {AuthContext} from '../Context/AuthContext'; const Navbar=props=>{ const{isAuthenticated,user,setIsAuthenticated,setUser,balance,setBalance}=useContext(AuthContext); const onClickLogoutHandler=() =>{ AuthService.logout().then(data=>{ if(data.success){ setUser(data.user); setIsAuthenticated(false); } }) } useEffect(()=> { fetch('user/get-balance',{ headers:{ 'Content-Type':"application/json" }, method:"POST", body:JSON.stringify({username:user.username}) }).then(res=>{ const response=res.json(); response.then(data=>{ console.log(data); setBalance(data.balance); }) }).catch(error=>{ console.log(error); }); },[user.username,isAuthenticated]); const unauthenticatedNavbar=() =>{ return( <> <li> <Link to='/'> Home </Link> </li> <li> <Link to='/login'> Login </Link> </li> <li> <Link to='/register'> Register </Link> </li> </> ) } const AuthenticatedNavbar=() =>{ return( <> <li> <Link to='/'> Home </Link> </li> { user.role==="admin" ? <li> <Link to='/admin'> Admin </Link> </li>:null } <li> <Link to='/map'> Map </Link> </li> <li> <Link to='/profile'> Profile </Link> </li> <li> <Link to='/search'> Search </Link> </li> <li> <button type='button' className='waves-effect waves-light green darken-2 btn' onClick={onClickLogoutHandler}> <Link to='/'> LOG OUT </Link> </button> </li> </> ) } return( <nav className="nav-extended red darken-2"> <div className="nav-wrapper red darken-2"> <div className='container'> <Link to='#'> <div className="brand-logo">Crave Better</div> </Link> <ul id="nav-mobile" className="right"> {!isAuthenticated ? unauthenticatedNavbar():AuthenticatedNavbar()} </ul> </div> </div> </nav> ) } export default Navbar;
import * as types from '../constants/actiontypes'; export default function(state = null, action) { switch (action.type) { case types.GET_SELECTED_EVENT: return action.apiResult; break; case types.GET_ATTENDEES: return Object.assign({}, state, {attendeesList: action.apiResult}); break; case types.GET_NOT_ATTEND: return Object.assign({}, state, {notAttendList: action.apiResult}); break; case types.GET_MAY_ATTEND: return Object.assign({}, state, {mayAttendList: action.apiResult}); break; case types.EVENT_POSTS: return Object.assign({}, state, {postsList: action.apiResult}); break; case types.EVENT_GALLERY: return Object.assign({}, state, {gallery: action.apiResult}); console.log("gallery",action.apiResult); break; case types.INVITIES_LIST: return Object.assign({}, state, {invitiesList: action.apiResult}); break; case types.SEARCH_INVITIES_LIST: return Object.assign({}, state, {searchInvitiesList: action.apiResult}); break; case types.GET_TEEFILES_LIST: return Object.assign({}, state, {teeFiles: action.apiResult}); break; } return state; }
if (!guru.GUILabel) { guru.GUILabel = function(value, id) { this._value = value || ""; this._id = id || guru.createID(); this._element = document.createElement("span"); this._element.appendChild(document.createTextNode(this._value)); this._element.id = this._id; this._element.className = "guru-gui-label"; this.onclick = function() {}; var that = this; this._element.onclick = function(e) { that.onclick(e); }; }; guru.GUILabel.prototype.center = function() { this._innerElement = this._element; this._element = document.createElement("div"); this._element.id = this._id; this._element.style.width = "100%"; this._element.style["box-sizing"] = "border-box"; this._element.style.display = "block"; this._element.style.textAlign = "center"; this._innerElement.style.display = "inline-block"; this._element.appendChild(this._innerElement); return this; }; guru.GUILabel.prototype.setPlaceholder = function(value) { if (this._innerElement) { this._innerElement.placeholder = value; } else { this._element.placeholder = value; } return this; }; guru.GUILabel.prototype.applyStyle = function(key, value) { if (typeof value === "Number") { value = value.toString() + "px"; } if (this._innerElement) { this._innerElement.style[key] = value; } else { this._element.style[key] = value; } return this; }; guru.GUILabel.prototype.setPosition = function(x, y) { this._element.style.position = "absolute"; this._element.style.top = y.toString() + "px"; this._element.style.left = x.toString() + "px"; return this; }; guru.GUILabel.prototype.setOnclick = function(onclick) { this.onclick = onclick; return this; }; guru.GUILabel.prototype.setValue = function(value) { this._value = value || ""; if(this._innerElement) { this._innerElement.innerHTML = this._value; } else { this._element.innerHTML = this._value; } }; }
import { StatusBar } from 'expo-status-bar'; import React, { useState, useEffect } from 'react'; import { StyleSheet, View, ScrollView, Text } from 'react-native'; import { deleteTopic, getTopics, setVisibleFalse } from '../../redux/actions/forum'; import { useDispatch, useSelector } from 'react-redux'; import theme from '../../constants/theme'; import Foot from '../../components/foot'; import AppSnackBar from '../../components/snackbar'; import Loading from '../../components/loading'; import AppListItem from '../../components/listItem'; import Icon from 'react-native-vector-icons/FontAwesome'; export default function EventDetailsScreen({ navigation, route }) { const event = route.params; return ( <View style={styles.container}> <View style={styles.titleContainer}> <Icon name={"chevron-left"} size={20} color="black" onPress={() => navigation.goBack()} /> <Text style={styles.bigTitle}>{event.name}</Text> </View> <View style={styles.detailsContainer}> <Text style={styles.title}>Description</Text> <Text style={styles.text}>{event.description}</Text> <Text style={styles.title}>Location</Text> <Text style={styles.text}>{event.location}</Text> <Text style={styles.title}>Time</Text> <Text style={styles.text}>{event.time}</Text> <Text style={styles.title}>Date</Text> <Text style={styles.text}>{event.date}</Text> <Text style={styles.title}>Organizer</Text> <Text style={styles.text}>{event.user.username}</Text> </View> </View> ) } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'white', alignItems: 'center', width: '100%', }, titleContainer: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', margin: 25, marginBottom: 0 }, detailsContainer: { flex: 8, backgroundColor: theme.colors.pink, width: '100%', borderTopStartRadius: 30, borderTopEndRadius: 30, padding: 25 }, title: { fontSize: theme.fontSizes.cardTitle, fontFamily: theme.fonts.bold, color: 'white', marginBottom: 10, }, text: { fontSize: theme.fontSizes.cardText, fontFamily: theme.fonts.regular, marginBottom: 30, color: 'white' }, bigTitle: { fontSize: theme.fontSizes.screenTitle, fontFamily: theme.fonts.bold, color: theme.colors.pink, marginLeft: 25, width: '90%', }, });