language
stringclasses
5 values
text
stringlengths
15
988k
JavaScript
class PerspectiveCamera extends Camera { /** * Creates a new PerspectiveCamera. * @param {Number} fovy Field-of-view angle across the y-axis. * @param {Number} aspect Aspect ratio of the camera viewport. * @param {Number} near Distance to the near plane. * @param {Number} far Distance to the far plane. */ constructor(fovy, aspect, near, far) { super(); mat4.perspective(this.proj, fovy, aspect, near, far); this.dirty = true; } }
JavaScript
class OrthogonalCamera extends Camera { /** * Creates a new OrthogonalCamera. * @param {Number} left Coordinate of the left side of the bounding box * @param {Number} right Coordinate of the right side of the bounding box * @param {Number} bottom Coordinate of the bottom side of the bounding box * @param {Number} top Coordinate of the top side of the bounding box * @param {Number} near Coordinate of the near side of the bounding box * @param {Number} far Coordinate of the far side of the bounding box */ constructor(left, right, bottom, top, near, far) { super(); mat4.ortho(this.proj, left, right, bottom, top, near, far); this.dirty = true; } }
JavaScript
class GroupCard extends React.Component { state ={ newPubcrawlClicked:false, existingCrawlClicked:false, editPubcrawlClicked: false } componentDidMount = () => { Adapter.fetchPubCrawls() .then(pubcrawls => this.props.setPubCrawls(pubcrawls)) } deleteGroup = (group_id) => { Adapter.fetchDeleteGroup(group_id) let deletedGroup = this.props.groups.find(group => group.id === group_id) this.props.removeGroup(deletedGroup) } deletePubCrawl = (pubcrawl) => { Adapter.fetchDeletePubCrawl(pubcrawl.id) let deletedPubCrawl = this.props.pubcrawls.find(pc => pc.id === pubcrawl.id) this.props.removePubCrawl(deletedPubCrawl) } addFriendToGroup = (friend, group_id) => { Adapter.fetchAddFriendToGroup(friend.id, group_id) this.props.addUserToGroup(friend, group_id) } createNewPubCrawl = (id) => { this.setState({newPubcrawlClicked:!this.state.newPubcrawlClicked}) let groupObj = this.props.groups.find(group => group.id === this.props.id) this.props.setCurrentGroup(groupObj) this.props.clearCrawl() } viewPubCrawl = (pubcrawl) => { this.setState({existingCrawlClicked:!this.state.existingCrawlClicked}) Adapter.fetchPubCrawls() .then(data => { let foundPubcrawl = data.find(data => data.id === pubcrawl.id) this.props.setCurrentPubCrawl(foundPubcrawl) }) } filterCrawls = () => { return this.props.pubcrawls.filter(pubcrawl => pubcrawl.group_id === this.props.id) } deleteUserFromUserGroup = (user_groups, group) => { let foundUG = user_groups.find(ug => ug.group_id === group.id) console.log(foundUG); Adapter.fetchDeleteFriendFromGroup(foundUG.id) this.props.deleteUserFromGroup(foundUG) } render() { console.log(this.props); const groupCard = <div className='groupcard'> {this.props.creator_id === this.props.user.id ? <DeleteIcon className="small material-icons" id='trash' onClick={()=>this.deleteGroup(this.props.id)}>delete_forever</DeleteIcon> : null} <List> <ListItem> <ListItemText align='center' primary=<h2> {`Name of Group: ${this.props.name}`}</h2>> </ListItemText> </ListItem> <ListItem> <ListItemText align='flex-start' primary={this.props.usersfromgroup.length > 0 ? <h3 style={{textDecorationLine:'underline'}}>Current users in Group {this.props.name}:</h3> : null} secondary={this.props.usersfromgroup.map(user => <h3 style={{textDecorationLine:null}} key={user.id}> {user.name}{this.props.creator_id === this.props.user.id ? <i onClick={()=>this.deleteUserFromUserGroup(user.user_groups, this.props)}className="material-icons">cancel</i> : null} </h3> )}> </ListItemText> </ListItem> <ListItem> <ListItemText primary= <h3 style={{textDecorationLine:'underline'}}> Your Friends </h3> secondary={this.props.friends.filter(friend => friend.id !== this.props.creator_id).map(f => <h3 key={f.id}> {f.name}: <span key={f.id}>{this.props.usersfromgroup.find(user => user.id === f.id) ? ` Officially a member of ${this.props.name}` : <i className="material-icons" onClick={()=>this.addFriendToGroup(f, this.props.id) }>person_add</i>}</span></h3> )}> </ListItemText> </ListItem> <ListItem> <ListItemText align='left'> {this.filterCrawls().length > 0 ? <h4 style={{textDecorationLine:'underline'}}> Your Pubcrawls with this Group: </h4> : null} {this.filterCrawls().map(pubcrawl => ( <div key={pubcrawl.id}> Pubcrawl id: {pubcrawl.id} <br/> <Button onClick={()=> this.viewPubCrawl(pubcrawl)}>View This Pubcrawl!<i className="material-icons">people</i></Button><br/> {this.props.creator_id === this.props.user.id ? <Button onClick={()=>this.deletePubCrawl(pubcrawl)}>Delete This Pubcrawl!<DeleteIcon onClick={()=>this.deletePubCrawl(pubcrawl)}></DeleteIcon></Button> : null} </div> ))} </ListItemText> </ListItem> <Button variant='contained' color='secondary' fullWidth onClick={()=>this.createNewPubCrawl(this.props.id)}>Create New Pub Crawl With {this.props.name}</Button> </List> </div> return this.state.newPubcrawlClicked || this.state.editPubcrawlClicked ? <Redirect to='/pubcrawl'/> : this.state.existingCrawlClicked ? <Redirect to='mypubcrawl'/> : groupCard } }
JavaScript
class CodeButton extends UpdatingButton { /** * Constructor */ constructor( toolbar ) { super( toolbar, OPTIONS ); } /** * Update override */ update( selectionState ) { this.disable( !selectionState.canCode ); this.activate( selectionState.isCode ); } }
JavaScript
class UserBasicInfo extends React.Component { static propTypes = { /** @ignore */ t: PropTypes.func.isRequired, /** @ignore */ theme: PropTypes.object.isRequired, /** @ignore */ isUpdatingCustomer: PropTypes.bool.isRequired, /** @ignore */ hasErrorUpdatingCustomer: PropTypes.bool.isRequired, /** @ignore */ firstName: PropTypes.string, /** @ignore */ lastName: PropTypes.string, /** @ignore */ dateOfBirth: PropTypes.string, /** @ignore */ generateAlert: PropTypes.func.isRequired, /** @ignore */ updateCustomer: PropTypes.func.isRequired, /** Component ID */ componentId: PropTypes.string.isRequired, /** @ignore */ navStack: PropTypes.array.isRequired, }; constructor(props) { super(props); this.state = { firstName: isNull(props.firstName) ? '' : props.firstName, lastName: isNull(props.lastName) ? '' : props.lastName, dateOfBirth: moment( props.dateOfBirth || // Using 1970 as default new Date(1970), ).format('DD/MM/YYYY'), }; } componentWillReceiveProps(nextProps) { if ( this.props.isUpdatingCustomer && !nextProps.isUpdatingCustomer && !nextProps.hasErrorUpdatingCustomer && last(this.props.navStack) === this.props.componentId ) { this.redirectToScreen('userAdvancedInfo'); } } /** * Navigates to chosen screen * * @method redirectToScreen */ redirectToScreen(screen) { navigator.push(screen); } /** * Pops the active screen from the navigation stack * @method goBack */ goBack() { navigator.pop(this.props.componentId); } /** * Updates customer information * * @method updateCustomer * * @returns {function} */ updateCustomer() { const { t } = this.props; if (!this.state.firstName) { return this.props.generateAlert( 'error', t('moonpay:invalidFirstName'), t('moonpay:invalidFirstNameExplanation'), ); } if (!this.state.lastName) { return this.props.generateAlert( 'error', t('moonpay:invalidLastName'), t('moonpay:invalidLastNameExplanation'), ); } const dobMoment = moment(this.state.dateOfBirth, 'DD/MM/YYYY'); if (!dobMoment.isValid()) { return this.props.generateAlert('error', t('moonpay:invalidDOB'), t('moonpay:invalidDOBExplanation')); } return this.props.updateCustomer({ firstName: this.state.firstName, lastName: this.state.lastName, dateOfBirth: dobMoment.toISOString(), }); } /** * Updates date of birth value * * @method updateDateOfBirth * * @param {string} newDateOfBirth * * @returns {void} */ updateDateOfBirth(newDateOfBirth) { const value = newDateOfBirth.replace(/\D/g, '').slice(0, 10); if (value.length >= 5) { this.setState({ dateOfBirth: `${value.slice(0, 2)}/${value.slice(2, 4)}/${value.slice(4, 8)}` }); } else if (value.length >= 3) { this.setState({ dateOfBirth: `${value.slice(0, 2)}/${value.slice(2)}` }); } else { this.setState({ dateOfBirth: value }); } } render() { const { t, theme, isUpdatingCustomer } = this.props; return ( <KeyboardAvoidingView style={[styles.container, { backgroundColor: theme.body.bg }]} behavior="position" keyboardVerticalOffset={10} enabled > <View> <View style={styles.topContainer}> <AnimatedComponent animationInType={['slideInRight', 'fadeIn']} animationOutType={['slideOutLeft', 'fadeOut']} delay={400} > <Header iconSize={width / 3} iconName="moonpay" textColor={theme.body.color} /> </AnimatedComponent> </View> <View style={styles.midContainer}> <AnimatedComponent animationInType={['slideInRight', 'fadeIn']} animationOutType={['slideOutLeft', 'fadeOut']} delay={320} > <InfoBox> <Text style={[styles.infoText, { color: theme.body.color }]}> {t('moonpay:tellUsAbout')} </Text> <Text style={[ styles.infoTextRegular, { paddingTop: height / 60, color: theme.body.color }, ]} > {t('moonpay:cardRegistrationName')} </Text> </InfoBox> </AnimatedComponent> <View style={{ flex: 0.6 }} /> <AnimatedComponent animationInType={['slideInRight', 'fadeIn']} animationOutType={['slideOutLeft', 'fadeOut']} delay={240} > <CustomTextInput label={t('moonpay:firstName')} onValidTextChange={(firstName) => this.setState({ firstName })} theme={theme} autoCorrect={false} enablesReturnKeyAutomatically returnKeyType="next" onSubmitEditing={() => { if (this.state.firstName) { this.lastName.focus(); } }} value={this.state.firstName} /> </AnimatedComponent> <View style={{ flex: 0.6 }} /> <AnimatedComponent animationInType={['slideInRight', 'fadeIn']} animationOutType={['slideOutLeft', 'fadeOut']} delay={160} > <CustomTextInput onRef={(c) => { this.lastName = c; }} label={t('moonpay:lastName')} onValidTextChange={(lastName) => this.setState({ lastName })} theme={theme} autoCorrect={false} enablesReturnKeyAutomatically returnKeyType="next" onSubmitEditing={() => { if (this.state.lastName) { this.dateOfBirth.focus(); } }} value={this.state.lastName} /> </AnimatedComponent> <View style={{ flex: 0.6 }} /> <AnimatedComponent animationInType={['slideInRight', 'fadeIn']} animationOutType={['slideOutLeft', 'fadeOut']} delay={80} > <CustomTextInput onRef={(c) => { this.dateOfBirth = c; }} label={t('moonpay:dateOfBirth')} onValidTextChange={(dateOfBirth) => this.updateDateOfBirth(dateOfBirth)} theme={theme} autoCorrect={false} enablesReturnKeyAutomatically returnKeyType="done" blurOnSubmit onSubmitEditing={() => Keyboard.dismiss()} value={this.state.dateOfBirth} placeholder="DD/MM/YYYY" /> </AnimatedComponent> <View style={{ flex: 0.6 }} /> </View> <View style={styles.bottomContainer}> <AnimatedComponent animationInType={['fadeIn']} animationOutType={['fadeOut']} delay={0}> <DualFooterButtons onLeftButtonPress={() => this.goBack()} onRightButtonPress={() => this.updateCustomer()} isRightButtonLoading={isUpdatingCustomer} disableLeftButton={isUpdatingCustomer} leftButtonText={t('global:goBack')} rightButtonText={t('global:continue')} leftButtonTestID="moonpay-back" rightButtonTestID="moonpay-next" /> </AnimatedComponent> </View> </View> </KeyboardAvoidingView> ); } }
JavaScript
class TableCell extends Component { constructor(props) { super(props) // this.state = { // activeHead: false, // activeCell: false, // } } render() { const styleBase = "m-0 text-gray-500 leading-none transition-color ease-in-out duration-300 cursor-pointer" const styleTH = styleBase + " pt-2 pb-1 border-r border-gray-700 hover:text-white hover:bg-gray-700 select-none" const styleTD = styleBase + " p-1 border-t border-r border-gray-700 hover:bg-gray-900" // const styleTDActive = "" const styleTDSpan = "p-1" const styleTDSpanActive = "text-gray-900 bg-cmykYellow-500 hover:bg-cmykYellow-200 rounded-sm" // = `bg-cmykRed-500 hover:bg-cmykRed-400 rounded-sm` const { // key, row, col, thead, active, handleActiveCell, handleRandomCell, children, } = this.props return ( <> {thead ? ( <th onClick={() => { handleRandomCell(col) }} className={styleTH} > {children.length > 0 && ( <div className={styleTDSpan}>{children}</div> )} </th> ) : ( <td onClick={() => { handleActiveCell(row, col) }} className={styleTD} > {children.length > 0 && ( <div className={styleTDSpan + ` ` + (active && styleTDSpanActive)} > {children} </div> )} </td> )} </> ) } }
JavaScript
class Range extends Core { constructor(options = {}) { options.id = Math.floor(Math.random() * 100000, 5).toString(); super(options); this._render(Template, options); this._findCurrentRangeValue = this._findCurrentRangeValue.bind(this); } _componentDidMount() { this._attachListener('change', '.hig__range__field', this.el, this._findCurrentRangeValue); // for IE11 this._attachListener('input', '.hig__range__field', this.el, this._findCurrentRangeValue); // for everyone else :/ } setInstructions(instructions) { if (instructions) { const instructionsEl = this._findOrAddElement('INSTRUCTIONS', 'p', '.hig__range__instructions'); instructionsEl.textContent = instructions; } else { this._removeElementIfFound('.hig__range__instructions'); } } setLabel(label) { if (label) { const labelEl = this._findOrAddElement('LABEL', 'label', '.hig__range__label'); labelEl.textContent = label; } else { this._removeElementIfFound('.hig__range__label'); } } setValue(value) { const field = this._findDOMEl('.hig__range__field', this.el); field.setAttribute('value', value); field.value = value; this._findDOMEl('.hig__range__field__current-value', this.el).textContent = value; this._findCurrentRangeValue(); } setMax(maxValue) { this._findDOMEl('.hig__range__field', this.el).setAttribute('max', maxValue); const dataset = this._findDOMEl('.hig__range__field__range-values', this.el).dataset; if (dataset) { dataset.rangeMax = maxValue; } } setMin(minValue) { this._findDOMEl('.hig__range__field', this.el).setAttribute('min', minValue); const dataset = this._findDOMEl('.hig__range__field__range-values', this.el).dataset; if (dataset) { dataset.rangeMin = minValue; } } setStep(value) { this._findDOMEl('.hig__range__field', this.el).setAttribute('step', value); } onBlur(fn) { return this._attachListener('focusout', '.hig__range__field', this.el, fn); } onChange(fn) { return this._attachListener('change', '.hig__range__field', this.el, fn); } onFocus(fn) { return this._attachListener('focusin', '.hig__range__field', this.el, fn); } onInput(fn) { return this._attachListener('input', '.hig__range__field', this.el, fn); } disable() { this._findDOMEl('.hig__range__field', this.el).setAttribute('disabled', true); this.el.classList.add('hig__range--disabled'); } enable() { this._findDOMEl('.hig__range__field', this.el).removeAttribute('disabled'); this.el.classList.remove('hig__range--disabled'); } required(requiredLabelText) { this.el.classList.add('hig__range--required'); const requiredNoticeEl = this._findOrAddElement('REQUIRED-NOTICE', 'p', '.hig__range__required-notice'); requiredNoticeEl.textContent = requiredLabelText; } noLongerRequired() { this.el.classList.remove('hig__range--required'); this._removeElementIfFound('.hig__range__required-notice'); } _findCurrentRangeValue() { const currentValue = this._findDOMEl('.hig__range__field', this.el).value; this._findDOMEl('.hig__range__field__current-value', this.el).textContent = currentValue; } }
JavaScript
class Queue { constructor() { this.front = null; this.back = null; }; // adds new node to the back nq(val) { let node = new Node(val); if (this.isEmpty()){ this.front = node; this.back = node; } else { this.back.next = node; this.back = this.back.next }; }; // removes node at the front and returns dq() { if (!this.isEmpty()){ let temp = this.front; this.front = this.front.next; temp.next = null; return temp.value; } else { return 'empty'; }; }; // looks at node at the front peek() { if (!this.front){ return null; } else if (this.front){ return this.front.value; }; }; // returns true/false whether or not queue is empty isEmpty() { if (this.front){ return false; } else if (!this.front){ return true; } else { throw new Error('Something went wrong'); }; }; }
JavaScript
class MessagesView extends React.Component { constructor(props) { super(props); this.state = { messagesJson: { } }; props.setParentReference(this.addMessageToView); } /* Adds a messageToAdd to the view. Note that the messageToAdd is expected to be an object with the following format: { "messageId" : { message: "some message", mine: true/false, time: *a Date object indicating when the message was created* } } "messageId" is indeed a string used as the key for the actual message that will be added to the messages view. */ addMessageToView(messageToAdd) { var event = new CustomEvent("newMessage", { detail: { messageToAdd: messageToAdd }}); // trigger the "newMessage" event document.dispatchEvent(event); } renderAllMessages() { var { messagesJson } = this.state; // list of messages to return var messages = []; for (var message in messagesJson) { var time = messagesJson[message].time; // if time is a not Dates object (happens for not "mine" messages) if (!(time instanceof Date)) { // then time will be an ISO string, so it has to be converted to a Date object time = new Date(time); } var hours = time.getHours(); var minutes = time.getMinutes(); // add a leading 0 if hours < 10 and if minutes < 10 if (hours < 10) { hours = "0" + hours; } if (minutes < 10) { minutes = "0" + minutes; } // change the time to a HH:MM format string time = hours + ":" + minutes; messages.push( <Message key = { message } message = { messagesJson[message].message } mine = { messagesJson[message].mine } time = { time } /> ); } return messages; } componentDidMount() { this.handler = (event) => { var messageToAdd = event.detail.messageToAdd; var nextId; // messageToAdd's id must be unique and follow the order of the this.state.messagesJson object's keys // if the messagesJson object has less than 1 element, set the id of the next message to 1 (it will be the initial message) if (Object.keys(this.state.messagesJson).length < 1) { nextId = 1; } // otherwise set the id to the biggest index in the object + 1 else { // get the key of the object with the highest key and increment it nextId = parseInt(Object.keys(this.state.messagesJson).reduce((a, b) => messageToAdd[a] > messageToAdd[b] ? a : b)) + 1; } // change the old "messageId" key to be nextId, so that the id is a unique number and can be displayed if ("messageId" !== nextId) { Object.defineProperty(messageToAdd, nextId, Object.getOwnPropertyDescriptor(messageToAdd, "messageId")); delete messageToAdd["messageId"]; } this.setState({messagesJson: {...this.state.messagesJson, ...messageToAdd}}); }; // is this allowed when using react? document.addEventListener("newMessage", this.handler); // get the socket from props var socket = this.props.socket; // if the socket was passed from the parent component if (socket) { // handle received messages socket.on("message", (data) => { // get the encryption key var encryptionKey = this.props.encryptionKey; // if the encryption key was set if (encryptionKey) { try { // get the encryption key and the iv from the parameters passed from the parent component to encrypt the message to the other client // the encryption key was converted to a hex string representation, so now it should be converted to a byte representation var key = forge.util.hexToBytes(encryptionKey); var iv = this.props.iv; // get the byte representation of the message from its receieved hex representation var encrypted = data.message.message; // decipher the message var decipher = forge.cipher.createDecipher('AES-CBC', key); decipher.start({iv: iv});console.log(encrypted) decipher.update(forge.util.createBuffer(forge.util.hexToBytes(encrypted))); var result = decipher.finish(); // if there was a problem with the decrypting if (!result) { console.error("There was an error with decrypting"); this.props.redirectToConnectionInterrupted(); } data.message.message = fromBase64(decipher.output.data); // add the message received from the server to the view this.addMessageToView({ "messageId": data.message }); // autoscroll if the user has not manually scrolled up setTimeout(function() { var scrollView = document.getElementById("messagesView"); // if the client has not scrolled up, autoscroll is activated if (Math.abs(scrollView.scrollTop - scrollView.scrollHeight) <= (scrollView.clientHeight + 44.5)) { // 44.5 can be replaced with (document.getElementsByClassName("compose")[0].clientHeight) scrollView.scrollTop = scrollView.scrollHeight; } }, 100); } catch(err) { console.error("There was an error with decrypting"); console.error(err); this.props.redirectToConnectionInterrupted(); } } }); } } // font-family: "Courier New", Courier, monospace; render() { return ( <div id = "messagesView"> <div style = {{textAlign: "center", fontFamily: "Courier" }}> <AsciiImage/> </div> { this.renderAllMessages() } </div> ); }; componentWillUnmount() { document.removeEventListener("newMessage", this.handler); } }
JavaScript
class FPSCtrl extends _FPSCtrl { /** * @param {number} fps - A Number indicating the times per second 'onFrame' gets called. * @param {onFrameCallback} onFrame - A callback function. * @param {object} [context] - A context the 'onFrame' functions gets bound to. * @constructor */ constructor (fps, onFrameCallback, object) { super(fps, onFrameCallback, object); this.mQueue = new NumberQueue(10); this.on('frame', () => { this.mQueue.enqueue(this.mTimer.getElapsedTime()); }); } /** * Returns the average time(in milliseconds) it took to compute the target function. * @returns {{averageTime: number, target: *}} */ getPerformanceInfo () { var tAvg = this.mQueue.getAverage() * 1000; return { averageTime: tAvg, fps: this.mMaxFPS, impact: this.isPlaying ? tAvg * this.mMaxFPS : 0, // returns average mSeconds per second target: this.mFunction, context: this.mContext ? this.mContext : null }; } }
JavaScript
class Scripts { /** * provide a context for all scripts added * @param context */ constructor (context) { this.mScripts = {}; this.mContext = context; this.mShared = {}; } /** * Add one script that will run as soon as the {@link play} method is called. * @param name - A unique script name which it is referenced by. * @param fps * @param handler * @returns {Scripts} */ add (name, fps, handler) { if (this.mScripts[name]) throw new Error('Script name must be unique. Dound duplicate for:' + name); if (this.mContext) { handler = handler.bind(this.mContext); } var that = this; var instance = new FPSCtrl(fps, function (e) { handler(e, that.mShared); }); this.mScripts[name] = {name, instance}; return this; } pause (selectors = '*') { var scripts = this.getMatchingScripts(selectors); for (var script of scripts) { script.instance.pause(); } return this; } /** * * @param selectors * @returns {Scripts} */ play (selectors = '*') { var scripts = this.getMatchingScripts(selectors); for (var script of scripts) { script.instance.start(); } return this; } getMatchingScripts (selectors) { var matches = []; var scripts = Object.keys(this.mScripts); var selectorsArray = selectors.split(','); for (var selector of selectorsArray) { var regexp = globStringToRegex(selector); for (var s of scripts) { if (s.match(regexp)) matches.push(this.mScripts[s]); } } return matches; } }
JavaScript
class ExtractionResponse extends DataMessage { /** * Constructs a new extraction response. */ constructor() { super(Action.EXTRACT); /** * A serialised isosurface. * * @type {Object} */ this.isosurface = null; } }
JavaScript
class Pending { static generateHash(objectFP, sourceFP, destinationFP) { return Crypto.hash(objectFP + '-' + sourceFP + '-' + destinationFP); } static dehidrateRecord(object, source, destination) { let objectFP = object.fingerprint(); let sourceFP = source.fingerprint(); let destinationFP = destination.fingerprint(); let hash = Pending.generateHash(objectFP, sourceFP, destinationFP); let timestamp = object.getTimestamp(); return { 'hash' : hash, 'object' : objectFP, 'source' : sourceFP, 'destination' : destinationFP, 'timestamp' : timestamp }; } }
JavaScript
class Hospital extends Component{ constructor(props){ super(props); this.grantAccess = this.grantAccess.bind(this); this.addPatientToInsuranceComp = this.addPatientToInsuranceComp.bind(this); this.registerDoc = this.registerDoc.bind(this); } contract =this.props.contract['OPT']; doctorAddRecord = this.props.contract['DAR']; accounts =this.props.Acc; state = { hosp_name:"", hosp_location:"", hosp_id:"" } //async methods and states here async loadHospital(){ try{ let res = await this.contract.methods.getHospitalInfo().call({from:this.accounts[0]}); this.setState({hosp_id:res[0],hosp_name:res[1],hosp_location:res[2]}); } catch(e){ console.log(e); } } async grantAccess(event){ event.preventDefault(); let requestor = document.getElementById('access_requestor').value; let patient = document.getElementById('access_of').value; console.log(requestor); console.log(patient); try{ let result = await this.contract.methods.hospitalGrantAccess(requestor,patient).send({"from":this.accounts[0]}); console.log(result); } catch(e){ console.log(e) } } componentDidMount(){ this.loadHospital(); } async addPatientToInsuranceComp(event){ event.preventDefault(); let addr1= document.getElementById('added_patient').value; let addr2= document.getElementById('added_to_company').value; try{ let result = await this.contract.methods.addPatientToInsuranceComp(addr2,addr1).send({"from":this.accounts[0]}); console.log(result); } catch(e){ console.log(e); } } async registerDoc(event) { event.preventDefault(true); let name = document.getElementById('doc_name').value; let id = document.getElementById('doc_id').value; let contact_info = document.getElementById('doc_contact').value; let specialization = document.getElementById('doc_specs').value; console.log(name); console.log(id); console.log(contact_info); console.log(specialization); await this.contract.methods.signupDoctor(id, name, contact_info, specialization).send({ from: this.accounts[0] }); } render(){ let {hosp_name, hosp_id, hosp_location} = this.state; return( <div className='container'> <Card> <div > <span><b>Id: </b>{hosp_id}</span> <br></br> <span><b>Name:</b> {hosp_name}</span> <br></br> <span><b>Location: </b>{hosp_location}</span> </div> </Card> <div className='row' style={{border:'1px black solid'}}> <div className='col'> <h5 style={{align:'centre'}}>Grant patient access to doctor</h5> <div> <form onSubmit={this.grantAccess}> <br></br> <div className="label mt-2"><b>Grant access to</b></div> <input type="text" name="Grant to" id="access_requestor"></input> <br></br> <div className="label mt-2"><b>Access of:</b></div> <input type="text" name="Access of" id="access_of" ></input> <br></br> <Button variant="dark" className="button" type="submit">Grant Access</Button> </form> </div> </div> </div> <div className='row mt-3' style={{border:'1px black solid'}}> <div className='col'> <h5 style={{align:'centre'}}>Add Patient To Insurance Comp.</h5> <div> <form onSubmit={this.addPatientToInsuranceComp}> <div className='label mt-2'>Patient Address:</div> <input type="text" id="added_patient" placeholder='Patient address'></input> <br></br> <div className='label mt-2'>Company Address:</div> <input type="text" id="added_to_company" placeholder='Company Address'></input> <br></br> <Button variant="dark" className="button" type="submit">Add</Button> </form> </div> </div> </div> <div className='row mt-3' style={{border:'1px black solid'}}> <div className='col'> <h5 style={{ align: 'centre' }}>Add Doctor To Blockchain</h5> <div style={{ marginLeft: '20px' }}> <form onSubmit={this.registerDoc}> <div className="label mt-2"><b>Name:</b></div> <input type="text" name="name" id="doc_name" placeholder="Name"></input> <br></br> <div className="label mt-2"><b>Blockchain Address:</b></div> <input type="text" name="name" id="doc_id" placeholder="Address"></input> <br></br> <div className="label mt-2"><b>Contact Info:</b></div> <input type="text" name="name" id="doc_contact" placeholder="Contact Info"></input> <br></br> <div className="label mt-2"><b>Specialization:</b></div> <input type="text" name="name" id="doc_specs" placeholder="Specialization"></input> <br></br> <Button variant="dark" className="button" type="submit">Register Doctor</Button> </form> </div> </div> </div> </div> ) } }
JavaScript
class AdminModuleController { /** * Initialize all listeners and bind everything * @method init * @memberof AdminModule */ constructor(moduleCardController) { this.moduleCardController = moduleCardController; this.DEFAULT_MAX_RECENTLY_USED = 10; this.DEFAULT_MAX_PER_CATEGORIES = 6; this.DISPLAY_GRID = 'grid'; this.DISPLAY_LIST = 'list'; this.CATEGORY_RECENTLY_USED = 'recently-used'; this.currentCategoryDisplay = {}; this.currentDisplay = ''; this.isCategoryGridDisplayed = false; this.currentTagsList = []; this.currentRefCategory = null; this.currentRefStatus = null; this.currentSorting = null; this.baseAddonsUrl = 'https://addons.prestashop.com/'; this.pstaggerInput = null; this.lastBulkAction = null; this.isUploadStarted = false; this.recentlyUsedSelector = '#module-recently-used-list .modules-list'; /** * Loaded modules list. * Containing the card and list display. * @type {Array} */ this.modulesList = []; this.addonsCardGrid = null; this.addonsCardList = null; this.moduleShortList = '.module-short-list'; // See more & See less selector this.seeMoreSelector = '.see-more'; this.seeLessSelector = '.see-less'; // Selectors into vars to make it easier to change them while keeping same code logic this.moduleItemGridSelector = '.module-item-grid'; this.moduleItemListSelector = '.module-item-list'; this.categorySelectorLabelSelector = '.module-category-selector-label'; this.categorySelector = '.module-category-selector'; this.categoryItemSelector = '.module-category-menu'; this.addonsLoginButtonSelector = '#addons_login_btn'; this.categoryResetBtnSelector = '.module-category-reset'; this.moduleInstallBtnSelector = 'input.module-install-btn'; this.moduleSortingDropdownSelector = '.module-sorting-author select'; this.categoryGridSelector = '#modules-categories-grid'; this.categoryGridItemSelector = '.module-category-item'; this.addonItemGridSelector = '.module-addons-item-grid'; this.addonItemListSelector = '.module-addons-item-list'; // Upgrade All selectors this.upgradeAllSource = '.module_action_menu_upgrade_all'; this.upgradeAllTargets = '#modules-list-container-update .module_action_menu_upgrade:visible'; // Bulk action selectors this.bulkActionDropDownSelector = '.module-bulk-actions'; this.bulkItemSelector = '.module-bulk-menu'; this.bulkActionCheckboxListSelector = '.module-checkbox-bulk-list input'; this.bulkActionCheckboxGridSelector = '.module-checkbox-bulk-grid input'; this.checkedBulkActionListSelector = `${this.bulkActionCheckboxListSelector}:checked`; this.checkedBulkActionGridSelector = `${this.bulkActionCheckboxGridSelector}:checked`; this.bulkActionCheckboxSelector = '#module-modal-bulk-checkbox'; this.bulkConfirmModalSelector = '#module-modal-bulk-confirm'; this.bulkConfirmModalActionNameSelector = '#module-modal-bulk-confirm-action-name'; this.bulkConfirmModalListSelector = '#module-modal-bulk-confirm-list'; this.bulkConfirmModalAckBtnSelector = '#module-modal-confirm-bulk-ack'; // Placeholders this.placeholderGlobalSelector = '.module-placeholders-wrapper'; this.placeholderFailureGlobalSelector = '.module-placeholders-failure'; this.placeholderFailureMsgSelector = '.module-placeholders-failure-msg'; this.placeholderFailureRetryBtnSelector = '#module-placeholders-failure-retry'; // Module's statuses selectors this.statusSelectorLabelSelector = '.module-status-selector-label'; this.statusItemSelector = '.module-status-menu'; this.statusResetBtnSelector = '.module-status-reset'; // Selectors for Module Import and Addons connect this.addonsConnectModalBtnSelector = '#page-header-desc-configuration-addons_connect'; this.addonsLogoutModalBtnSelector = '#page-header-desc-configuration-addons_logout'; this.addonsImportModalBtnSelector = '#page-header-desc-configuration-add_module'; this.dropZoneModalSelector = '#module-modal-import'; this.dropZoneModalFooterSelector = '#module-modal-import .modal-footer'; this.dropZoneImportZoneSelector = '#importDropzone'; this.addonsConnectModalSelector = '#module-modal-addons-connect'; this.addonsLogoutModalSelector = '#module-modal-addons-logout'; this.addonsConnectForm = '#addons-connect-form'; this.moduleImportModalCloseBtn = '#module-modal-import-closing-cross'; this.moduleImportStartSelector = '.module-import-start'; this.moduleImportProcessingSelector = '.module-import-processing'; this.moduleImportSuccessSelector = '.module-import-success'; this.moduleImportSuccessConfigureBtnSelector = '.module-import-success-configure'; this.moduleImportFailureSelector = '.module-import-failure'; this.moduleImportFailureRetrySelector = '.module-import-failure-retry'; this.moduleImportFailureDetailsBtnSelector = '.module-import-failure-details-action'; this.moduleImportSelectFileManualSelector = '.module-import-start-select-manual'; this.moduleImportFailureMsgDetailsSelector = '.module-import-failure-details'; this.moduleImportConfirmSelector = '.module-import-confirm'; this.initSortingDropdown(); this.initBOEventRegistering(); this.initCurrentDisplay(); this.initSortingDisplaySwitch(); this.initBulkDropdown(); this.initSearchBlock(); this.initCategorySelect(); this.initCategoriesGrid(); this.initActionButtons(); this.initAddonsSearch(); this.initAddonsConnect(); this.initAddModuleAction(); this.initDropzone(); this.initPageChangeProtection(); this.initPlaceholderMechanism(); this.initFilterStatusDropdown(); this.fetchModulesList(); this.getNotificationsCount(); this.initializeSeeMore(); } initFilterStatusDropdown() { const self = this; const body = $('body'); body.on('click', self.statusItemSelector, function () { // Get data from li DOM input self.currentRefStatus = parseInt($(this).data('status-ref'), 10); // Change dropdown label to set it to the current status' displayname $(self.statusSelectorLabelSelector).text($(this).find('a:first').text()); $(self.statusResetBtnSelector).show(); self.updateModuleVisibility(); }); body.on('click', self.statusResetBtnSelector, function () { $(self.statusSelectorLabelSelector).text($(this).find('a').text()); $(this).hide(); self.currentRefStatus = null; self.updateModuleVisibility(); }); } initBulkDropdown() { const self = this; const body = $('body'); body.on('click', self.getBulkCheckboxesSelector(), () => { const selector = $(self.bulkActionDropDownSelector); if ($(self.getBulkCheckboxesCheckedSelector()).length > 0) { selector.closest('.module-top-menu-item') .removeClass('disabled'); } else { selector.closest('.module-top-menu-item') .addClass('disabled'); } }); body.on('click', self.bulkItemSelector, function initializeBodyChange() { if ($(self.getBulkCheckboxesCheckedSelector()).length === 0) { $.growl.warning({message: window.translate_javascripts['Bulk Action - One module minimum']}); return; } self.lastBulkAction = $(this).data('ref'); const modulesListString = self.buildBulkActionModuleList(); const actionString = $(this).find(':checked').text().toLowerCase(); $(self.bulkConfirmModalListSelector).html(modulesListString); $(self.bulkConfirmModalActionNameSelector).text(actionString); if (self.lastBulkAction === 'bulk-uninstall') { $(self.bulkActionCheckboxSelector).show(); } else { $(self.bulkActionCheckboxSelector).hide(); } $(self.bulkConfirmModalSelector).modal('show'); }); body.on('click', this.bulkConfirmModalAckBtnSelector, (event) => { event.preventDefault(); event.stopPropagation(); $(self.bulkConfirmModalSelector).modal('hide'); self.doBulkAction(self.lastBulkAction); }); } initBOEventRegistering() { window.BOEvent.on('Module Disabled', this.onModuleDisabled, this); window.BOEvent.on('Module Uninstalled', this.updateTotalResults, this); } onModuleDisabled() { const self = this; const moduleItemSelector = self.getModuleItemSelector(); $('.modules-list').each(function scanModulesList() { self.updateTotalResults(); }); } initPlaceholderMechanism() { const self = this; if ($(self.placeholderGlobalSelector).length) { self.ajaxLoadPage(); } // Retry loading mechanism $('body').on('click', self.placeholderFailureRetryBtnSelector, () => { $(self.placeholderFailureGlobalSelector).fadeOut(); $(self.placeholderGlobalSelector).fadeIn(); self.ajaxLoadPage(); }); } ajaxLoadPage() { const self = this; $.ajax({ method: 'GET', url: window.moduleURLs.catalogRefresh, }).done((response) => { if (response.status === true) { if (typeof response.domElements === 'undefined') response.domElements = null; if (typeof response.msg === 'undefined') response.msg = null; const stylesheet = document.styleSheets[0]; const stylesheetRule = '{display: none}'; const moduleGlobalSelector = '.modules-list'; const moduleSortingSelector = '.module-sorting-menu'; const requiredSelectorCombination = `${moduleGlobalSelector},${moduleSortingSelector}`; if (stylesheet.insertRule) { stylesheet.insertRule( requiredSelectorCombination + stylesheetRule, stylesheet.cssRules.length ); } else if (stylesheet.addRule) { stylesheet.addRule( requiredSelectorCombination, stylesheetRule, -1 ); } $(self.placeholderGlobalSelector).fadeOut(800, () => { $.each(response.domElements, (index, element) => { $(element.selector).append(element.content); }); $(moduleGlobalSelector).fadeIn(800).css('display', 'flex'); $(moduleSortingSelector).fadeIn(800); $('[data-toggle="popover"]').popover(); self.initCurrentDisplay(); self.fetchModulesList(); }); } else { $(self.placeholderGlobalSelector).fadeOut(800, () => { $(self.placeholderFailureMsgSelector).text(response.msg); $(self.placeholderFailureGlobalSelector).fadeIn(800); }); } }).fail((response) => { $(self.placeholderGlobalSelector).fadeOut(800, () => { $(self.placeholderFailureMsgSelector).text(response.statusText); $(self.placeholderFailureGlobalSelector).fadeIn(800); }); }); } fetchModulesList() { const self = this; let container; let $this; self.modulesList = []; $('.modules-list').each(function prepareContainer() { container = $(this); container.find('.module-item').each(function prepareModules() { $this = $(this); self.modulesList.push({ domObject: $this, id: $this.data('id'), name: $this.data('name').toLowerCase(), scoring: parseFloat($this.data('scoring')), logo: $this.data('logo'), author: $this.data('author').toLowerCase(), version: $this.data('version'), description: $this.data('description').toLowerCase(), techName: $this.data('tech-name').toLowerCase(), childCategories: $this.data('child-categories'), categories: String($this.data('categories')).toLowerCase(), type: $this.data('type'), price: parseFloat($this.data('price')), active: parseInt($this.data('active'), 10), access: $this.data('last-access'), display: $this.hasClass('module-item-list') ? self.DISPLAY_LIST : self.DISPLAY_GRID, container, }); $this.remove(); }); }); self.addonsCardGrid = $(this.addonItemGridSelector); self.addonsCardList = $(this.addonItemListSelector); self.updateModuleVisibility(); $('body').trigger('moduleCatalogLoaded'); } /** * Prepare sorting * */ updateModuleSorting() { const self = this; if (!self.currentSorting) { return; } // Modules sorting let order = 'asc'; let key = self.currentSorting; const splittedKey = key.split('-'); if (splittedKey.length > 1) { key = splittedKey[0]; if (splittedKey[1] === 'desc') { order = 'desc'; } } const currentCompare = (a, b) => { let aData = a[key]; let bData = b[key]; if (key === 'access') { aData = (new Date(aData)).getTime(); bData = (new Date(bData)).getTime(); aData = isNaN(aData) ? 0 : aData; bData = isNaN(bData) ? 0 : bData; if (aData === bData) { return b.name.localeCompare(a.name); } } if (aData < bData) return -1; if (aData > bData) return 1; return 0; }; self.modulesList.sort(currentCompare); if (order === 'desc') { self.modulesList.reverse(); } } updateModuleContainerDisplay() { const self = this; $('.module-short-list').each(function setShortListVisibility() { const container = $(this); const nbModulesInContainer = container.find('.module-item').length; if ( ( self.currentRefCategory && self.currentRefCategory !== String(container.find('.modules-list').data('name')) ) || ( self.currentRefStatus !== null && nbModulesInContainer === 0 ) || ( nbModulesInContainer === 0 && String(container.find('.modules-list').data('name')) === self.CATEGORY_RECENTLY_USED ) || ( self.currentTagsList.length > 0 && nbModulesInContainer === 0 ) ) { container.hide(); return; } container.show(); if (nbModulesInContainer >= self.DEFAULT_MAX_PER_CATEGORIES) { container.find(`${self.seeMoreSelector}, ${self.seeLessSelector}`).show(); } else { container.find(`${self.seeMoreSelector}, ${self.seeLessSelector}`).hide(); } }); } updateModuleVisibility() { const self = this; self.updateModuleSorting(); $(self.recentlyUsedSelector).find('.module-item').remove(); $('.modules-list').find('.module-item').remove(); // Modules visibility management let isVisible; let currentModule; let moduleCategory; let tagExists; let newValue; const modulesListLength = self.modulesList.length; const counter = {}; for (let i = 0; i < modulesListLength; i += 1) { currentModule = self.modulesList[i]; if (currentModule.display === self.currentDisplay) { isVisible = true; moduleCategory = self.currentRefCategory === self.CATEGORY_RECENTLY_USED ? self.CATEGORY_RECENTLY_USED : currentModule.categories; // Check for same category if (self.currentRefCategory !== null) { isVisible &= moduleCategory === self.currentRefCategory; } // Check for same status if (self.currentRefStatus !== null) { isVisible &= currentModule.active === self.currentRefStatus; } // Check for tag list if (self.currentTagsList.length) { tagExists = false; $.each(self.currentTagsList, (index, value) => { newValue = value.toLowerCase(); tagExists |= ( currentModule.name.indexOf(newValue) !== -1 || currentModule.description.indexOf(newValue) !== -1 || currentModule.author.indexOf(newValue) !== -1 || currentModule.techName.indexOf(newValue) !== -1 ); }); isVisible &= tagExists; } /** * If list display without search we must display only the first 5 modules */ if (self.currentDisplay === self.DISPLAY_LIST && !self.currentTagsList.length) { if (self.currentCategoryDisplay[moduleCategory] === undefined) { self.currentCategoryDisplay[moduleCategory] = false; } if (!counter[moduleCategory]) { counter[moduleCategory] = 0; } if (moduleCategory === self.CATEGORY_RECENTLY_USED) { if (counter[moduleCategory] >= self.DEFAULT_MAX_RECENTLY_USED) { isVisible &= self.currentCategoryDisplay[moduleCategory]; } } else if (counter[moduleCategory] >= self.DEFAULT_MAX_PER_CATEGORIES) { isVisible &= self.currentCategoryDisplay[moduleCategory]; } counter[moduleCategory] += 1; } // If visible, display (Thx captain obvious) if (isVisible) { if (self.currentRefCategory === self.CATEGORY_RECENTLY_USED) { $(self.recentlyUsedSelector).append(currentModule.domObject); } else { currentModule.container.append(currentModule.domObject); } } } } self.updateModuleContainerDisplay(); if (self.currentTagsList.length) { $('.modules-list').append(this.currentDisplay === self.DISPLAY_GRID ? this.addonsCardGrid : this.addonsCardList); } self.updateTotalResults(); } initPageChangeProtection() { const self = this; $(window).on('beforeunload', () => { if (self.isUploadStarted === true) { return 'It seems some critical operation are running, are you sure you want to change page ? It might cause some unexepcted behaviors.'; } }); } buildBulkActionModuleList() { const checkBoxesSelector = this.getBulkCheckboxesCheckedSelector(); const moduleItemSelector = this.getModuleItemSelector(); let alreadyDoneFlag = 0; let htmlGenerated = ''; let currentElement; $(checkBoxesSelector).each(function prepareCheckboxes() { if (alreadyDoneFlag === 10) { // Break each htmlGenerated += '- ...'; return false; } currentElement = $(this).closest(moduleItemSelector); htmlGenerated += `- ${currentElement.data('name')}<br/>`; alreadyDoneFlag += 1; return true; }); return htmlGenerated; } initAddonsConnect() { const self = this; // Make addons connect modal ready to be clicked if ($(self.addonsConnectModalBtnSelector).attr('href') === '#') { $(self.addonsConnectModalBtnSelector).attr('data-toggle', 'modal'); $(self.addonsConnectModalBtnSelector).attr('data-target', self.addonsConnectModalSelector); } if ($(self.addonsLogoutModalBtnSelector).attr('href') === '#') { $(self.addonsLogoutModalBtnSelector).attr('data-toggle', 'modal'); $(self.addonsLogoutModalBtnSelector).attr('data-target', self.addonsLogoutModalSelector); } $('body').on('submit', self.addonsConnectForm, function initializeBodySubmit(event) { event.preventDefault(); event.stopPropagation(); $.ajax({ method: 'POST', url: $(this).attr('action'), dataType: 'json', data: $(this).serialize(), beforeSend: () => { $(self.addonsLoginButtonSelector).show(); $('button.btn[type="submit"]', self.addonsConnectForm).hide(); } }).done((response) => { if (response.success === 1) { location.reload(); } else { $.growl.error({message: response.message}); $(self.addonsLoginButtonSelector).hide(); $('button.btn[type="submit"]', self.addonsConnectForm).fadeIn(); } }); }); } initAddModuleAction() { const self = this; const addModuleButton = $(self.addonsImportModalBtnSelector); addModuleButton.attr('data-toggle', 'modal'); addModuleButton.attr('data-target', self.dropZoneModalSelector); } initDropzone() { const self = this; const body = $('body'); const dropzone = $('.dropzone'); // Reset modal when click on Retry in case of failure body.on( 'click', this.moduleImportFailureRetrySelector, () => { $(`${self.moduleImportSuccessSelector},${self.moduleImportFailureSelector},${self.moduleImportProcessingSelector}`).fadeOut(() => { /** * Added timeout for a better render of animation * and avoid to have displayed at the same time */ setTimeout(() => { $(self.moduleImportStartSelector).fadeIn(() => { $(self.moduleImportFailureMsgDetailsSelector).hide(); $(self.moduleImportSuccessConfigureBtnSelector).hide(); dropzone.removeAttr('style'); }); }, 550); }); } ); // Reinit modal on exit, but check if not already processing something body.on('hidden.bs.modal', this.dropZoneModalSelector, () => { $(`${self.moduleImportSuccessSelector}, ${self.moduleImportFailureSelector}`).hide(); $(self.moduleImportStartSelector).show(); dropzone.removeAttr('style'); $(self.moduleImportFailureMsgDetailsSelector).hide(); $(self.moduleImportSuccessConfigureBtnSelector).hide(); $(self.dropZoneModalFooterSelector).html(''); $(self.moduleImportConfirmSelector).hide(); }); // Change the way Dropzone.js lib handle file input trigger body.on( 'click', `.dropzone:not(${this.moduleImportSelectFileManualSelector}, ${this.moduleImportSuccessConfigureBtnSelector})`, (event, manualSelect) => { // if click comes from .module-import-start-select-manual, stop everything if (typeof manualSelect === 'undefined') { event.stopPropagation(); event.preventDefault(); } } ); body.on('click', this.moduleImportSelectFileManualSelector, (event) => { event.stopPropagation(); event.preventDefault(); /** * Trigger click on hidden file input, and pass extra data * to .dropzone click handler fro it to notice it comes from here */ $('.dz-hidden-input').trigger('click', ['manual_select']); }); // Handle modal closure body.on('click', this.moduleImportModalCloseBtn, () => { if (self.isUploadStarted !== true) { $(self.dropZoneModalSelector).modal('hide'); } }); // Fix issue on click configure button body.on('click', this.moduleImportSuccessConfigureBtnSelector, function initializeBodyClickOnModuleImport(event) { event.stopPropagation(); event.preventDefault(); window.location = $(this).attr('href'); }); // Open failure message details box body.on('click', this.moduleImportFailureDetailsBtnSelector, () => { $(self.moduleImportFailureMsgDetailsSelector).slideDown(); }); // @see: dropzone.js const dropzoneOptions = { url: window.moduleURLs.moduleImport, acceptedFiles: '.zip, .tar', // The name that will be used to transfer the file paramName: 'file_uploaded', maxFilesize: 50, // can't be greater than 50Mb because it's an addons limitation uploadMultiple: false, addRemoveLinks: true, dictDefaultMessage: '', hiddenInputContainer: self.dropZoneImportZoneSelector, /** * Add unlimited timeout. Otherwise dropzone timeout is 30 seconds * and if a module is long to install, it is not possible to install the module. */ timeout: 0, addedfile: () => { self.animateStartUpload(); }, processing: () => { // Leave it empty since we don't require anything while processing upload }, error: (file, message) => { self.displayOnUploadError(message); }, complete: (file) => { if (file.status !== 'error') { const responseObject = $.parseJSON(file.xhr.response); if (typeof responseObject.is_configurable === 'undefined') responseObject.is_configurable = null; if (typeof responseObject.module_name === 'undefined') responseObject.module_name = null; self.displayOnUploadDone(responseObject); } // State that we have finish the process to unlock some actions self.isUploadStarted = false; }, }; dropzone.dropzone($.extend(dropzoneOptions)); } animateStartUpload() { const self = this; const dropzone = $('.dropzone'); // State that we start module upload self.isUploadStarted = true; $(self.moduleImportStartSelector).hide(0); dropzone.css('border', 'none'); $(self.moduleImportProcessingSelector).fadeIn(); } animateEndUpload(callback) { const self = this; $(self.moduleImportProcessingSelector).finish().fadeOut(callback); } /** * Method to call for upload modal, when the ajax call went well. * * @param object result containing the server response */ displayOnUploadDone(result) { const self = this; self.animateEndUpload(() => { if (result.status === true) { if (result.is_configurable === true) { const configureLink = window.moduleURLs.configurationPage.replace(/:number:/, result.module_name); $(self.moduleImportSuccessConfigureBtnSelector).attr('href', configureLink); $(self.moduleImportSuccessConfigureBtnSelector).show(); } $(self.moduleImportSuccessSelector).fadeIn(); } else if (typeof result.confirmation_subject !== 'undefined') { self.displayPrestaTrustStep(result); } else { $(self.moduleImportFailureMsgDetailsSelector).html(result.msg); $(self.moduleImportFailureSelector).fadeIn(); } }); } /** * Method to call for upload modal, when the ajax call went wrong or when the action requested could not * succeed for some reason. * * @param string message explaining the error. */ displayOnUploadError(message) { const self = this; self.animateEndUpload(() => { $(self.moduleImportFailureMsgDetailsSelector).html(message); $(self.moduleImportFailureSelector).fadeIn(); }); } /** * If PrestaTrust needs to be confirmed, we ask for the confirmation * modal content and we display it in the currently displayed one. * We also generate the ajax call to trigger once we confirm we want to install * the module. * * @param Previous server response result */ displayPrestaTrustStep(result) { const self = this; const modal = self.moduleCardController._replacePrestaTrustPlaceholders(result); const moduleName = result.module.attributes.name; $(this.moduleImportConfirmSelector).html(modal.find('.modal-body').html()).fadeIn(); $(this.dropZoneModalFooterSelector).html(modal.find('.modal-footer').html()).fadeIn(); $(this.dropZoneModalFooterSelector).find('.pstrust-install').off('click').on('click', () => { $(self.moduleImportConfirmSelector).hide(); $(self.dropZoneModalFooterSelector).html(''); self.animateStartUpload(); // Install ajax call $.post(result.module.attributes.urls.install, {'actionParams[confirmPrestaTrust]': '1'}) .done((data) => { self.displayOnUploadDone(data[moduleName]); }) .fail((data) => { self.displayOnUploadError(data[moduleName]); }) .always(() => { self.isUploadStarted = false; }); }); } getBulkCheckboxesSelector() { return this.currentDisplay === this.DISPLAY_GRID ? this.bulkActionCheckboxGridSelector : this.bulkActionCheckboxListSelector; } getBulkCheckboxesCheckedSelector() { return this.currentDisplay === this.DISPLAY_GRID ? this.checkedBulkActionGridSelector : this.checkedBulkActionListSelector; } getModuleItemSelector() { return this.currentDisplay === this.DISPLAY_GRID ? this.moduleItemGridSelector : this.moduleItemListSelector; } /** * Get the module notifications count and displays it as a badge on the notification tab * @return void */ getNotificationsCount() { const self = this; $.getJSON( window.moduleURLs.notificationsCount, self.updateNotificationsCount ).fail(() => { console.error('Could not retrieve module notifications count.'); }); } updateNotificationsCount(badge) { const destinationTabs = { to_configure: $('#subtab-AdminModulesNotifications'), to_update: $('#subtab-AdminModulesUpdates'), }; for (let key in destinationTabs) { if (destinationTabs[key].length === 0) { continue; } destinationTabs[key].find('.notification-counter').text(badge[key]); } } initAddonsSearch() { const self = this; $('body').on( 'click', `${self.addonItemGridSelector}, ${self.addonItemListSelector}`, () => { let searchQuery = ''; if (self.currentTagsList.length) { searchQuery = encodeURIComponent(self.currentTagsList.join(' ')); } window.open(`${self.baseAddonsUrl}search.php?search_query=${searchQuery}`, '_blank'); } ); } initCategoriesGrid() { const self = this; $('body').on('click', this.categoryGridItemSelector, function initilaizeGridBodyClick(event) { event.stopPropagation(); event.preventDefault(); const refCategory = $(this).data('category-ref'); // In case we have some tags we need to reset it ! if (self.currentTagsList.length) { self.pstaggerInput.resetTags(false); self.currentTagsList = []; } const menuCategoryToTrigger = $(`${self.categoryItemSelector}[data-category-ref="${refCategory}"]`); if (!menuCategoryToTrigger.length) { console.warn(`No category with ref (${refCategory}) seems to exist!`); return false; } // Hide current category grid if (self.isCategoryGridDisplayed === true) { $(self.categoryGridSelector).fadeOut(); self.isCategoryGridDisplayed = false; } // Trigger click on right category $(`${self.categoryItemSelector}[data-category-ref="${refCategory}"]`).click(); return true; }); } initCurrentDisplay() { this.currentDisplay = this.currentDisplay === '' ? this.DISPLAY_LIST : this.DISPLAY_GRID; } initSortingDropdown() { const self = this; self.currentSorting = $(this.moduleSortingDropdownSelector).find(':checked').attr('value'); if (!self.currentSorting) { self.currentSorting = 'access-desc'; } $('body').on( 'change', self.moduleSortingDropdownSelector, function initializeBodySortingChange() { self.currentSorting = $(this).find(':checked').attr('value'); self.updateModuleVisibility(); } ); } doBulkAction(requestedBulkAction) { // This object is used to check if requested bulkAction is available and give proper // url segment to be called for it const forceDeletion = $('#force_bulk_deletion').prop('checked'); const bulkActionToUrl = { 'bulk-uninstall': 'uninstall', 'bulk-disable': 'disable', 'bulk-enable': 'enable', 'bulk-disable-mobile': 'disable_mobile', 'bulk-enable-mobile': 'enable_mobile', 'bulk-reset': 'reset', }; // Note no grid selector used yet since we do not needed it at dev time // Maybe useful to implement this kind of things later if intended to // use this functionality elsewhere but "manage my module" section if (typeof bulkActionToUrl[requestedBulkAction] === 'undefined') { $.growl.error({message: window.translate_javascripts['Bulk Action - Request not found'].replace('[1]', requestedBulkAction)}); return false; } // Loop over all checked bulk checkboxes const bulkActionSelectedSelector = this.getBulkCheckboxesCheckedSelector(); const bulkModuleAction = bulkActionToUrl[requestedBulkAction]; if ($(bulkActionSelectedSelector).length <= 0) { console.warn(window.translate_javascripts['Bulk Action - One module minimum']); return false; } const modulesActions = []; let moduleTechName; $(bulkActionSelectedSelector).each(function bulkActionSelector() { moduleTechName = $(this).data('tech-name'); modulesActions.push({ techName: moduleTechName, actionMenuObj: $(this).closest('.module-checkbox-bulk-list').next(), }); }); this.performModulesAction(modulesActions, bulkModuleAction, forceDeletion); return true; } performModulesAction(modulesActions, bulkModuleAction, forceDeletion) { const self = this; if (typeof self.moduleCardController === 'undefined') { return; } //First let's filter modules that can't perform this action let actionMenuLinks = filterAllowedActions(modulesActions); if (!actionMenuLinks.length) { return; } let modulesRequestedCountdown = actionMenuLinks.length - 1; let spinnerObj = $("<button class=\"btn-primary-reverse onclick unbind spinner \"></button>"); if (actionMenuLinks.length > 1) { //Loop through all the modules except the last one which waits for other //requests and then call its request with cache clear enabled $.each(actionMenuLinks, function bulkModulesLoop(index, actionMenuLink) { if (index >= actionMenuLinks.length - 1) { return; } requestModuleAction(actionMenuLink, true, countdownModulesRequest); }); //Display a spinner for the last module const lastMenuLink = actionMenuLinks[actionMenuLinks.length - 1]; const actionMenuObj = lastMenuLink.closest(self.moduleCardController.moduleItemActionsSelector); actionMenuObj.hide(); actionMenuObj.after(spinnerObj); } else { requestModuleAction(actionMenuLinks[0]); } function requestModuleAction(actionMenuLink, disableCacheClear, requestEndCallback) { self.moduleCardController._requestToController( bulkModuleAction, actionMenuLink, forceDeletion, disableCacheClear, requestEndCallback ); } function countdownModulesRequest() { modulesRequestedCountdown--; //Now that all other modules have performed their action WITHOUT cache clear, we //can request the last module request WITH cache clear if (modulesRequestedCountdown <= 0) { if (spinnerObj) { spinnerObj.remove(); spinnerObj = null; } const lastMenuLink = actionMenuLinks[actionMenuLinks.length - 1]; const actionMenuObj = lastMenuLink.closest(self.moduleCardController.moduleItemActionsSelector); actionMenuObj.fadeIn(); requestModuleAction(lastMenuLink); } } function filterAllowedActions(modulesActions) { let actionMenuLinks = []; let actionMenuLink; $.each(modulesActions, function filterAllowedModules(index, moduleData) { actionMenuLink = $( self.moduleCardController.moduleActionMenuLinkSelector + bulkModuleAction, moduleData.actionMenuObj ); if (actionMenuLink.length > 0) { actionMenuLinks.push(actionMenuLink); } else { $.growl.error({message: window.translate_javascripts['Bulk Action - Request not available for module'] .replace('[1]', bulkModuleAction) .replace('[2]', moduleData.techName)}); } }); return actionMenuLinks; } } initActionButtons() { const self = this; $('body').on( 'click', self.moduleInstallBtnSelector, function initializeActionButtonsClick(event) { const $this = $(this); const $next = $($this.next()); event.preventDefault(); $this.hide(); $next.show(); $.ajax({ url: $this.data('url'), dataType: 'json', }).done(() => { $next.fadeOut(); }); } ); // "Upgrade All" button handler $('body').on('click', self.upgradeAllSource, (event) => { event.preventDefault(); if ($(self.upgradeAllTargets).length <= 0) { console.warn(window.translate_javascripts['Upgrade All Action - One module minimum']); return false; } const modulesActions = []; let moduleTechName; $(self.upgradeAllTargets).each(function bulkActionSelector() { const moduleItemList = $(this).closest('.module-item-list'); moduleTechName = moduleItemList.data('tech-name'); modulesActions.push({ techName: moduleTechName, actionMenuObj: $('.module-actions', moduleItemList), }); }); this.performModulesAction(modulesActions, 'upgrade'); return true; }); } initCategorySelect() { const self = this; const body = $('body'); body.on( 'click', self.categoryItemSelector, function initializeCategorySelectClick() { // Get data from li DOM input self.currentRefCategory = $(this).data('category-ref'); self.currentRefCategory = self.currentRefCategory ? String(self.currentRefCategory).toLowerCase() : null; // Change dropdown label to set it to the current category's displayname $(self.categorySelectorLabelSelector).text($(this).data('category-display-name')); $(self.categoryResetBtnSelector).show(); self.updateModuleVisibility(); } ); body.on( 'click', self.categoryResetBtnSelector, function initializeCategoryResetButtonClick() { const rawText = $(self.categorySelector).attr('aria-labelledby'); const upperFirstLetter = rawText.charAt(0).toUpperCase(); const removedFirstLetter = rawText.slice(1); const originalText = upperFirstLetter + removedFirstLetter; $(self.categorySelectorLabelSelector).text(originalText); $(this).hide(); self.currentRefCategory = null; self.updateModuleVisibility(); } ); } initSearchBlock() { const self = this; self.pstaggerInput = $('#module-search-bar').pstagger({ onTagsChanged: (tagList) => { self.currentTagsList = tagList; self.updateModuleVisibility(); }, onResetTags: () => { self.currentTagsList = []; self.updateModuleVisibility(); }, inputPlaceholder: window.translate_javascripts['Search - placeholder'], closingCross: true, context: self, }); $('body').on('click', '.module-addons-search-link', (event) => { event.preventDefault(); event.stopPropagation(); window.open($(this).attr('href'), '_blank'); }); } /** * Initialize display switching between List or Grid */ initSortingDisplaySwitch() { const self = this; $('body').on( 'click', '.module-sort-switch', function switchSort() { const switchTo = $(this).data('switch'); const isAlreadyDisplayed = $(this).hasClass('active-display'); if (typeof switchTo !== 'undefined' && isAlreadyDisplayed === false) { self.switchSortingDisplayTo(switchTo); self.currentDisplay = switchTo; } } ); } switchSortingDisplayTo(switchTo) { if (switchTo !== this.DISPLAY_GRID && switchTo !== this.DISPLAY_LIST) { console.error(`Can't switch to undefined display property "${switchTo}"`); return; } $('.module-sort-switch').removeClass('module-sort-active'); $(`#module-sort-${switchTo}`).addClass('module-sort-active'); this.currentDisplay = switchTo; this.updateModuleVisibility(); } initializeSeeMore() { const self = this; $(`${self.moduleShortList} ${self.seeMoreSelector}`).on('click', function seeMore() { self.currentCategoryDisplay[$(this).data('category')] = true; $(this).addClass('d-none'); $(this).closest(self.moduleShortList).find(self.seeLessSelector).removeClass('d-none'); self.updateModuleVisibility(); }); $(`${self.moduleShortList} ${self.seeLessSelector}`).on('click', function seeMore() { self.currentCategoryDisplay[$(this).data('category')] = false; $(this).addClass('d-none'); $(this).closest(self.moduleShortList).find(self.seeMoreSelector).removeClass('d-none'); self.updateModuleVisibility(); }); } updateTotalResults() { const replaceFirstWordBy = (element, value) => { const explodedText = element.text().split(' '); explodedText[0] = value; element.text(explodedText.join(' ')); }; // If there are some shortlist: each shortlist count the modules on the next container. const $shortLists = $('.module-short-list'); if ($shortLists.length > 0) { $shortLists.each(function shortLists() { const $this = $(this); replaceFirstWordBy( $this.find('.module-search-result-wording'), $this.next('.modules-list').find('.module-item').length ); }); // If there is no shortlist: the wording directly update from the only module container. } else { const modulesCount = $('.modules-list').find('.module-item').length; replaceFirstWordBy($('.module-search-result-wording'), modulesCount); const selectorToToggle = (self.currentDisplay === self.DISPLAY_LIST) ? this.addonItemListSelector : this.addonItemGridSelector; $(selectorToToggle).toggle(modulesCount !== (this.modulesList.length / 2)); if (modulesCount === 0) { $('.module-addons-search-link').attr( 'href', `${this.baseAddonsUrl}search.php?search_query=${encodeURIComponent(this.currentTagsList.join(' '))}` ); } } } }
JavaScript
class WasiView extends DataView { /** * Read a dirent structure. * * https://github.com/WebAssembly/WASI/blob/HEAD/phases/snapshot/docs.md#-dirent-struct */ getDirent(byteOffset, littleEndian = false) { /* * typedef struct __wasi_dirent_t { * __wasi_dircookie_t d_next; u64 * __wasi_inode_t d_ino; u64 * uint32_t d_namlen; u32 * __wasi_filetype_t d_type; u8 * <pad> u8 * <pad> u16 * } __wasi_dirent_t; */ return { d_next: this.getBigUint64(byteOffset, littleEndian), d_ino: this.getBigUint64(byteOffset + 8, littleEndian), d_namelen: this.getUint32(byteOffset + 16, littleEndian), d_type: this.getUint8(byteOffset + 20, littleEndian), length: 24, }; } /** * Write a fdstat structure. * * https://github.com/WebAssembly/WASI/blob/HEAD/phases/snapshot/docs.md#fdstat */ setFdstat(byteOffset, value, littleEndian = false) { /* * typedef struct __wasi_fdstat_t { * __wasi_filetype_t fs_filetype; u8 * <pad> u8 * __wasi_fdflags_t fs_flags; u16 * <pad> u32 * __wasi_rights_t fs_rights_base; u64 * __wasi_rights_t fs_rights_inheriting; u64 * } __wasi_fdstat_t; */ this.setUint8(byteOffset, value.filetype, littleEndian); this.setUint16(byteOffset + 2, 0, littleEndian); this.setBigUint64(byteOffset + 8, value.rights_base, littleEndian); this.setBigUint64(byteOffset + 16, value.rights_inheriting, littleEndian); } /** * Write a filestat structure. * * https://github.com/WebAssembly/WASI/blob/HEAD/phases/snapshot/docs.md#filestat */ setFilestat(byteOffset, value, littleEndian = false) { /* * typedef struct __wasi_filestat_t { * __wasi_device_t st_dev; u64 * __wasi_inode_t st_ino; u64 * __wasi_filetype_t st_filetype; u8 * <pad> u8 * __wasi_linkcount_t st_nlink; u32 * __wasi_filesize_t st_size; u64 * __wasi_timestamp_t st_atim; u64 * __wasi_timestamp_t st_mtim; u64 * __wasi_timestamp_t st_ctim; u64 * } __wasi_filestat_t; */ } /** * Read an iovec/ciovec structure. * * https://github.com/WebAssembly/WASI/blob/HEAD/phases/snapshot/docs.md#-iovec-struct * https://github.com/WebAssembly/WASI/blob/HEAD/phases/snapshot/docs.md#-ciovec-struct */ getIovec(byteOffset, littleEndian = false) { /* * typedef struct __wasi_iovec_t { * void *buf; u32 * size_t buf_len; u32 * } __wasi_iovec_t; */ return { buf: this.getUint32(byteOffset, littleEndian), buf_len: this.getUint32(byteOffset + 4, littleEndian), length: 8, }; } }
JavaScript
class IndecisionApp extends React.Component { state = { options : this.props.options, optionSelected : this.props.optionSelected }; removeAll=()=>{ this.setState(()=>({ options : [] })); } removeOne=(optionToRemove)=>{ console.log("Its working",optionToRemove); this.setState((prevState) =>{ return { options : prevState.options.filter((option)=> { return optionToRemove !==option; } )} }); } getRandom=()=>{ const randomOption=Math.floor(Math.random()*this.state.options.length); const selected = this.state.options[randomOption]; this.setState(()=>({ optionSelected : selected })); /* alert(selected); */ } closeModal=()=>{ this.setState(()=>({ optionSelected : false })); } /* Function to add an option */ addOption=(input)=>{ /* console.log("Add option ! "); */ /* Do validation */ if(!input) { return 'Provide an option please'; } else if(this.state.options.indexOf(input) > -1 ){ return `This already exists !` } this.setState((prevState)=>{ return { options : prevState.options.concat(input) }; }); } /* Lifecycle methods */x componentDidMount() { try { const json = localStorage.getItem('options'); const options = JSON.parse(json); if (options) { this.setState(() => ({ options })); } } catch (e) { // Do nothing at all } } componentDidUpdate(prevProps, prevState) { if (prevState.options.length !== this.state.options.length) { const json = JSON.stringify(this.state.options); localStorage.setItem('options', json); } } render() { const jsx = ( <div > <Header title={title} subtitle={subtitle}/> <div className="container"> <Action hasOptions={this.state.options.length > 0} options={this.state.options} removeAll={this.removeAll} getRandom={this.getRandom} /> <div className="widget"> <Options options={this.state.options} removeOne={this.removeOne} /> <AddOption addOption={this.addOption} /> </div> <OpenModal optionSelected={this.state.optionSelected} closeModal={this.closeModal} /> </div> </div> ); return jsx; } }
JavaScript
class FunctionalClosure extends Closure { /** * @param {string} name the name of the clousre * @param {Function} fn a function providing an implementation * for this closure. */ constructor(name, fn, options) { super(name, options); if (typeof(fn) !== "function") { throw new TypeError(`Implementation for provided closure '${name}' is not a function`); } this.fn = fn; } /** * Evaluates the block against a fact promise * @param {Object} fact a fact * @param {Context} context an execution context. * @param {Context} context.engine the rules engine * * @return {Object|Promise} a promise that will be resolved to some result */ process(fact, context) { return this.fn.call(this, fact, context); } }
JavaScript
class JSONAPISerializer extends Serializer { contentType = 'application/vnd.api+json'; /** * Take a response body (a model, an array of models, or an Error) and render * it as a JSONAPI compliant document * * @method serialize * @param {Response} response * @param {Object} options */ serialize(response, options = {}) { let document = {}; this.renderPrimary(response.body, document, options); this.renderIncluded(response.body, document, options); this.renderMeta(response.body, document, options); this.renderLinks(response.body, document, options); this.renderVersion(response.body, document, options); this.dedupeIncluded(document); response.body = document; response.contentType = this.contentType; } /** * Render the primary payload for a JSONAPI document (either a model or array * of models). * * @method renderPrimary * @see {@link http://jsonapi.org/format/#document-top-level|JSONAPI spec} * @param {Object|Array} payload errors or models to render * @param {Object} document top level document to render into * @param {Object} options */ renderPrimary(payload, document, options) { if (isArray(payload)) { this.renderPrimaryArray(payload, document, options); } else { return this.renderPrimaryObject(payload, document, options); } } renderPrimaryObject(payload, document, options) { if (payload instanceof Error) { document.errors = [ this.renderError(payload, options) ]; } else { document.data = this.renderRecord(payload, document, options); } } renderPrimaryArray(payload, document, options) { if (payload[0] instanceof Error) { document.errors = payload.map((error) => { assert(error instanceof Error, 'You passed a mixed array of errors and models to the JSON-API serializer. The JSON-API spec does not allow for both `data` and `errors` top level objects in a response'); return this.renderError(error, options); }); } else { document.data = payload.map((record) => { assert(!(record instanceof Error), 'You passed a mixed array of errors and models to the JSON-API serializer. The JSON-API spec does not allow for both `data` and `errors` top level objects in a response'); return this.renderRecord(record, document, options); }); } } /** * Render any included records into the top level of the document * * @method renderIncluded * @param {Object|Array} payload * @param {Object} document top level JSONAPI document * @param {Object} options * @param {Object} options.included array of records to sideload */ renderIncluded(payload, document, options) { if (options.included) { assert(isArray(options.included), 'included records must be passed in as an array'); document.included = options.included.map((includedRecord) => { return this.renderRecord(includedRecord, options); }); } } /** * Render top level meta object for a document. Default uses meta supplied in * options call to res.render(). * * @method renderMeta * @param {Object|Array} payload * @param {Object} document top level JSONAPI document * @param {Object} options * @param {Object} options.meta */ renderMeta(payload, document, options) { if (options.meta) { document.meta = options.meta; } } /** * Render top level links object for a document. Defaults to the links * supplied in options, or the URL for the invoking action if no links are * supplied. * * @method renderLinks * @param {Object|Array} payload * @param {Object} document top level JSONAPI document * @param {Object} options * @param {Object} options.links */ renderLinks(payload, document, options) { if (options.links) { document.links = options.links; } } /** * Render the version of JSONAPI supported. * * @method renderVersion * @param {Object|Array} payload * @param {Object} document top level JSONAPI document * @param {Object} options */ renderVersion(payload, document) { document.jsonapi = { version: '1.0' }; } /** * Render the supplied record as a resource object. * * @method renderRecord * @see {@link http://jsonapi.org/format/#document-resource-objects|JSONAPI spec} * @param {Object} options * @param {Object} record * @return {Object} a resource object representing the record */ renderRecord(record, document, options = {}) { assert(record, `Cannot serialize ${ record }. You supplied ${ record } instead of a Model instance.`); let serializedRecord = { type: pluralize(record.constructor.type), id: record.id }; assert(serializedRecord.id != null, `Attempted to serialize a record (${ record }) without an id, but the JSON-API spec requires all resources to have an id.`); // Makes it a little less onerous than passing these three args everywhere let context = { record, document, options }; setIfNotEmpty(serializedRecord, 'attributes', this.attributesForRecord(context)); setIfNotEmpty(serializedRecord, 'relationships', this.relationshipsForRecord(context)); setIfNotEmpty(serializedRecord, 'links', this.linksForRecord(context)); setIfNotEmpty(serializedRecord, 'meta', this.metaForRecord(context)); return serializedRecord; } /** * Returns the JSONAPI attributes object representing this record's * relationships * * @method attributesForRecord * @see {@link http://jsonapi.org/format/#document-resource-object-attributes|JSONAPI spec} * @param {Object} record * @param {Object} options * @return {Object} the JSONAPI attributes object */ attributesForRecord({ record }) { let serializedAttributes = {}; this.attributes.forEach((attributeName) => { let key = this.serializeAttributeName(attributeName); let rawValue = record[attributeName]; if (!isUndefined(rawValue)) { let value = this.serializeAttributeValue(rawValue, key, record); serializedAttributes[key] = value; } }); return serializedAttributes; } /** * The JSONAPI spec recommends (but does not require) that property names be * dasherized. The default implementation of this serializer therefore does * that, but you can override this method to use a different approach. * * @method serializeAttributeName * @param {name} name the attribute name to serialize * @return {String} the attribute name, dasherized */ serializeAttributeName(name) { return kebabCase(name); } /** * Take an attribute value and return the serialized value. Useful for * changing how certain types of values are serialized, i.e. Date objects. * * The default implementation returns the attribute's value unchanged. * * @method serializeAttributeValue * @param {*} value * @param {String} key * @param {Object} record * @return {*} the value that should be rendered */ serializeAttributeValue(value/* , key, record */) { return value; } /** * Returns the JSONAPI relationships object representing this record's * relationships * * @method relationshipsForRecord * @see http://jsonapi.org/format/#document-resource-object-relationships * @param {Object} record * @param {Object} options * @return {Object} the JSONAPI relationships object */ relationshipsForRecord(context) { let { record, options } = context; let serializedRelationships = {}; // The result of this.relationships is a whitelist of which relationships // should be serialized, and the configuration for their serialization let relationships = typeof this.relationships === 'function' ? this.relationships.call(options.action) : this.relationships; forEach(relationships, (config) => { let key = config.key || this.serializeRelationshipName(config.name); let descriptor = record.constructor[config.name]; assert(descriptor, `You specified a '${ config.name }' relationship in your ${ record.constructor.type } serializer, but no such relationship is defined on the ${ record.constructor.type } model`); serializedRelationships[key] = this.serializeRelationship(config, descriptor, context); }); return serializedRelationships; } /** * Takes the serializer config and the model's descriptor for a relationship, * and returns the serialized relationship object. Also sideloads any full * records found for the relationship. * * @static * @method serializeRelationship * @param {Object} config the options provided at the serializer for this relationship * @param {Object} descriptor the model's descriptor for this relationship * @param {Object} context * @return {Object} the serialized relationship object */ serializeRelationship(config, descriptor, context) { let relationship = {}; let dataMethod = this[`dataFor${ capitalize(descriptor.mode) }`]; setIfNotEmpty(relationship, 'links', this.linksForRelationship(config, descriptor, context)); setIfNotEmpty(relationship, 'data', dataMethod.call(this, config, descriptor, context)); setIfNotEmpty(relationship, 'meta', this.metaForRelationship(config, descriptor, context)); return relationship; } /** * Given the serializer config and the model descriptor for a hasOne * relationship, returns the data for that relationship (the resource object * with type and id). Sideloads the related record if present. * * @static * @method dataForHasOne * @param {Object} config the options provided at the serializer for this relationship * @param {Object} descriptor the model's descriptor for this relationship * @param {Object} context * @return {Object} the serialized data object for the relationship */ dataForHasOne(config, descriptor, context) { let { record } = context; let relatedRecordOrId = record.getRelated(config.name); return this.dataForRelatedRecord(config, descriptor, context, relatedRecordOrId); } /** * Given the serializer config and the model descriptor for a hasMany * relationship, returns the data for that relationship (the resource objects * with type and id). Sideloads the related records if present. * * @static * @method dataForHasMany * @param {Object} config the options provided at the serializer for this relationship * @param {Object} descriptor the model's descriptor for this relationship * @param {Object} context * @return {Object} the serialized data array for the relationship */ dataForHasMany(config, descriptor, context) { let { record } = context; let relatedRecords = record.getRelated(config.name); return relatedRecords.map(this.dataForRelatedRecord.bind(this, config, descriptor, context)); } /** * Given a related record or it's id, return the resource object for that * record (or id). If it's a full record, sideload the record as well. * * @static * @method dataForRelatedRecord * @param {Model|Number|String} relatedRecordOrId the related record or it's id * @param {Object} config the options provided at the serializer for this relationship * @param {Object} descriptor the model's descriptor for this relationship * @param {Object} context * @return {Object} the serialized resource object for the given related record or id */ dataForRelatedRecord(relatedRecordOrId, { name, type }, descriptor, context) { if (relatedRecordOrId instanceof Model) { this.includeRecord(name, relatedRecordOrId, descriptor, context); return { type: pluralize(relatedRecordOrId.constructor.type), id: relatedRecordOrId.id }; } return { type, id: relatedRecordOrId }; } /** * Takes a relationship descriptor and the record it's for, and returns any * links for that relationship for that record. I.e. '/books/1/author' * * @method linksForRelationship * @param {String} name name of the relationship * @param {Object} descriptor descriptor for the relationship * @param {Object} record parent record containing the * relationships * @return {Object} the links object for the supplied * relationship */ linksForRelationship({ name }, descriptor, context) { let recordURL = this.linksForRecord(context).self; return { self: path.join(recordURL, `relationships/${ name }`), related: path.join(recordURL, name) }; } /** * Returns any meta for a given relationship and record. No meta included by * default. * * @method metaForRelationship * @param {String} name name of the relationship * @param {Object} descriptor descriptor for the relationship * @param {Object} record parent record containing the * relationship * @param {Object} options * @return {Object} */ metaForRelationship() {} /** * Returns links for a particular record, i.e. self: "/books/1". Default * implementation assumes the URL for a particular record maps to that type's * `show` action, i.e. `books/show`. * * @method linksForRecord * @param {Object} record [description] * @param {Object} options [description] * @return {Object} [description] */ linksForRecord({ record }) { let router = this.container.lookup('router:main'); let url = router.urlFor(`${ pluralize(record.constructor.type) }/show`, record); return url ? { self: url } : null; } /** * Returns meta for a particular record. * * @method metaForRecord * @param {Object} record * @param {Object} options * @return {Object} */ metaForRecord() {} /** * Sideloads a record into the top level "included" array * * @method includeRecord * @private * @param {Object} record the record to sideload * @param {Object} descriptor * @param {Object} descriptor.config * @param {Object} descriptor.config.type * @param {Object} descriptor.config.strategy * @param {Object} descriptor.data * @param {Object} document the top level JSONAPI document * @param {Object} options */ includeRecord(config, descriptor, context) { let { record, document, options } = context; if (!isArray(document.included)) { document.included = []; } let relatedOptions = (options.relationships && options.relationships[config.name]) || options; let relatedSerializer = config.serializer || this.container.lookup(`serializer:${ record.constructor.type }`); document.included.push(relatedSerializer.renderRecord(record, document, relatedOptions)); } /** * Render the supplied error * * @method renderError * @param {Error} error * @return {Object} the JSONAPI error object */ renderError(error) { let renderedError = { id: error.id, status: error.status || 500, code: error.code || error.name || 'InternalServerError', title: error.title, detail: error.message }; setIfNotEmpty(renderedError, 'source', this.sourceForError(error)); setIfNotEmpty(renderedError, 'meta', this.metaForError(error)); setIfNotEmpty(renderedError, 'links', this.linksForError(error)); return renderedError; } /** * Given an error, return a JSON Pointer, a URL query param name, or other * info indicating the source of the error. * * @method sourceForError * @see {@link http://jsonapi.org/format/#error-objects|JSONAPI spec} * @param {Error} error * @return {Object} an error source object, optionally including a * "pointer" JSON Pointer or "parameter" for the * query param that caused the error. */ sourceForError(error) { return error.source; } /** * Return the meta for a given error object. You could use this for example, * to return debug information in development environments. * * @method metaForError * @param {Error} error * @return {Object} */ metaForError(error) { return error.meta; } /** * Return a links object for an error. You could use this to link to a bug * tracker report of the error, for example. * * @method linksForError * @param {Error} error * @return {Object} */ linksForError() {} /** * Remove duplicate entries from the sideloaded data. * * @method dedupeIncluded * @private * @param {Object} document the top level JSONAPI document */ dedupeIncluded(document) { if (isArray(document.included)) { document.included = uniq(document.included, (resource) => { return `${ resource.type }/${ resource.id }`; }); } } /** * Unlike the other serializers, the default parse implementation does modify * the incoming payload. It converts the default dasherized attribute names * into camelCase. * * The parse method here retains the JSONAPI document structure (i.e. data, * included, links, meta, etc), only modifying resource objects in place. * * @method parse * @param payload {Object} the JSONAPI document to parse * @return {Object} the parsed payload */ parse(payload) { try { assert(payload.data, 'Invalid JSON-API document (missing top level `data` object - see http://jsonapi.org/format/#document-top-level)'); let parseResource = this._parseResource.bind(this); if (payload.data) { if (!isArray(payload.data)) { payload.data = parseResource(payload.data); } else { payload.data = payload.data.map(parseResource); } } if (payload.included) { payload.included = payload.included.map(parseResource); } } catch (e) { if (e.name === 'AssertionError') { throw new Errors.BadRequest(e.message); } throw e; } return payload; } /** * Takes a JSON-API resource object and hands it off for parsing to the * serializer specific to that object's type. * * @method _parseResource * @param resource {Object} a JSON-API resource object POJO * @return {Object} the parsed result * @private */ _parseResource(resource) { assert(typeof resource.type === 'string', 'Invalid resource object encountered (missing `type` - see http://jsonapi.org/format/#document-resource-object-identification)'); resource.type = this.parseType(resource.type); let relatedSerializer = this.container.lookup(`serializer:${ resource.type }`); return relatedSerializer.parseResource(resource); } /** * Parse a single resource object from a JSONAPI document. The resource object * could come from the top level `data` payload, or from the sideloaded * `included` records. * * @method parseResource * @param resource {Object} a JSONAPI resource object * @return {Object} the parsed resource object. Note: do not return an ORM * instance from this method - that is handled separately. */ parseResource(resource) { setIfNotEmpty(resource, 'id', this.parseId(resource.id)); setIfNotEmpty(resource, 'attributes', this.parseAttributes(resource.attributes)); setIfNotEmpty(resource, 'relationships', this.parseRelationships(resource.relationships)); return resource; } /** * Parse a resource object id * * @method parseId * @param {String|Number} id * @return {String|Number} the parsed id */ parseId(id) { return id; } /** * Parse a resource object's type string * * @method parseType * @param {String} type * @return {String} the parsed type */ parseType(type) { return singularize(type); } /** * Parse a resource object's attributes. By default, this converts from the * JSONAPI recommended dasheried keys to camelCase. * * @method parseAttributes * @param {Object} attrs * @return {Object} the parsed attributes */ parseAttributes(attrs) { return mapKeys(attrs, (value, key) => { return camelCase(key); }); } /** * Parse a resource object's relationships. By default, this converts from the * JSONAPI recommended dasheried keys to camelCase. * * @method parseRelationships * @param {Object} relationships * @return {Object} the parsed relationships */ parseRelationships(relationships) { return mapKeys(relationships, (value, key) => { return camelCase(key); }); } }
JavaScript
class BillDataInfo extends AbstractModel { constructor(){ super(); /** * Time point in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.Time = null; /** * Bandwidth in Mbps. * @type {number || null} */ this.Bandwidth = null; /** * Traffic in MB. * @type {number || null} */ this.Flux = null; /** * Time point of peak value in the format of `yyyy-mm-dd HH:MM:SS`. As raw data is at a 5-minute granularity, if data at a 1-hour or 1-day granularity is queried, the time point of peak bandwidth value at the corresponding granularity will be returned. * @type {string || null} */ this.PeakTime = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null; this.Flux = 'Flux' in params ? params.Flux : null; this.PeakTime = 'PeakTime' in params ? params.PeakTime : null; } }
JavaScript
class TemplateInfo extends AbstractModel { constructor(){ super(); /** * Codec: h264/h265/origin. Default value: h264. origin: keep the original codec. * @type {string || null} */ this.Vcodec = null; /** * Video bitrate. Value range: 0–8,000 Kbps. If the value is 0, the original bitrate will be retained. Note: transcoding templates require a unique bitrate. The final saved bitrate may differ from the input bitrate. * @type {number || null} */ this.VideoBitrate = null; /** * Audio codec: aac. Default value: aac. Note: This parameter will not take effect for now and will be supported soon. * @type {string || null} */ this.Acodec = null; /** * Audio bitrate. Value range: 0–500 Kbps. 0 by default. * @type {number || null} */ this.AudioBitrate = null; /** * Width. Default value: 0. Value range: [0-3,000]. The value must be a multiple of 2. The original width is 0. * @type {number || null} */ this.Width = null; /** * Height. Default value: 0. Value range: [0-3,000]. The value must be a multiple of 2. The original width is 0. * @type {number || null} */ this.Height = null; /** * Frame rate. Default value: 0. Range: 0-60 Fps. * @type {number || null} */ this.Fps = null; /** * Keyframe interval, unit: second. Original interval by default Range: 2-6 * @type {number || null} */ this.Gop = null; /** * Rotation angle. Default value: 0. Value range: 0, 90, 180, 270 * @type {number || null} */ this.Rotate = null; /** * Encoding quality: baseline/main/high. Default value: baseline. * @type {string || null} */ this.Profile = null; /** * Whether to use the original bitrate when the set bitrate is larger than the original bitrate. 0: no, 1: yes Default value: 0. * @type {number || null} */ this.BitrateToOrig = null; /** * Whether to use the original height when the set height is higher than the original height. 0: no, 1: yes Default value: 0. * @type {number || null} */ this.HeightToOrig = null; /** * Whether to use the original frame rate when the set frame rate is larger than the original frame rate. 0: no, 1: yes Default value: 0. * @type {number || null} */ this.FpsToOrig = null; /** * Whether to keep the video. 0: no; 1: yes. * @type {number || null} */ this.NeedVideo = null; /** * Whether to keep the audio. 0: no; 1: yes. * @type {number || null} */ this.NeedAudio = null; /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Template name. * @type {string || null} */ this.TemplateName = null; /** * Template description. * @type {string || null} */ this.Description = null; /** * Whether it is a top speed codec template. 0: no, 1: yes. Default value: 0. * @type {number || null} */ this.AiTransCode = null; /** * Bitrate compression ratio of top speed code video. Target bitrate of top speed code = VideoBitrate * (1-AdaptBitratePercent) Value range: 0.0-0.5. * @type {number || null} */ this.AdaptBitratePercent = null; /** * Whether to take the shorter side as height. 0: no, 1: yes. Default value: 0. Note: this field may return `null`, indicating that no valid value is obtained. * @type {number || null} */ this.ShortEdgeAsHeight = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Vcodec = 'Vcodec' in params ? params.Vcodec : null; this.VideoBitrate = 'VideoBitrate' in params ? params.VideoBitrate : null; this.Acodec = 'Acodec' in params ? params.Acodec : null; this.AudioBitrate = 'AudioBitrate' in params ? params.AudioBitrate : null; this.Width = 'Width' in params ? params.Width : null; this.Height = 'Height' in params ? params.Height : null; this.Fps = 'Fps' in params ? params.Fps : null; this.Gop = 'Gop' in params ? params.Gop : null; this.Rotate = 'Rotate' in params ? params.Rotate : null; this.Profile = 'Profile' in params ? params.Profile : null; this.BitrateToOrig = 'BitrateToOrig' in params ? params.BitrateToOrig : null; this.HeightToOrig = 'HeightToOrig' in params ? params.HeightToOrig : null; this.FpsToOrig = 'FpsToOrig' in params ? params.FpsToOrig : null; this.NeedVideo = 'NeedVideo' in params ? params.NeedVideo : null; this.NeedAudio = 'NeedAudio' in params ? params.NeedAudio : null; this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.TemplateName = 'TemplateName' in params ? params.TemplateName : null; this.Description = 'Description' in params ? params.Description : null; this.AiTransCode = 'AiTransCode' in params ? params.AiTransCode : null; this.AdaptBitratePercent = 'AdaptBitratePercent' in params ? params.AdaptBitratePercent : null; this.ShortEdgeAsHeight = 'ShortEdgeAsHeight' in params ? params.ShortEdgeAsHeight : null; } }
JavaScript
class PushAuthKeyInfo extends AbstractModel { constructor(){ super(); /** * Domain name. * @type {string || null} */ this.DomainName = null; /** * Whether to enable. 0: disabled; 1: enabled. * @type {number || null} */ this.Enable = null; /** * Master authentication key. * @type {string || null} */ this.MasterAuthKey = null; /** * Standby authentication key. * @type {string || null} */ this.BackupAuthKey = null; /** * Validity period in seconds. * @type {number || null} */ this.AuthDelta = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.Enable = 'Enable' in params ? params.Enable : null; this.MasterAuthKey = 'MasterAuthKey' in params ? params.MasterAuthKey : null; this.BackupAuthKey = 'BackupAuthKey' in params ? params.BackupAuthKey : null; this.AuthDelta = 'AuthDelta' in params ? params.AuthDelta : null; } }
JavaScript
class PushQualityData extends AbstractModel { constructor(){ super(); /** * Data time in the format of `%Y-%m-%d %H:%M:%S.%ms` and accurate down to the millisecond level. * @type {string || null} */ this.Time = null; /** * Push domain name. * @type {string || null} */ this.PushDomain = null; /** * Push path. * @type {string || null} */ this.AppName = null; /** * Push client IP. * @type {string || null} */ this.ClientIp = null; /** * Push start time in the format of `%Y-%m-%d %H:%M:%S.%ms` and accurate down to the millisecond level. * @type {string || null} */ this.BeginPushTime = null; /** * Resolution information. * @type {string || null} */ this.Resolution = null; /** * Video codec. * @type {string || null} */ this.VCodec = null; /** * Audio codec. * @type {string || null} */ this.ACodec = null; /** * Push serial number, which uniquely identifies a push. * @type {string || null} */ this.Sequence = null; /** * Video frame rate. * @type {number || null} */ this.VideoFps = null; /** * Video bitrate in bps. * @type {number || null} */ this.VideoRate = null; /** * Audio frame rate. * @type {number || null} */ this.AudioFps = null; /** * Audio bitrate in bps. * @type {number || null} */ this.AudioRate = null; /** * Local elapsed time in milliseconds. The greater the difference between audio/video elapsed time and local elapsed time, the poorer the push quality and the more serious the upstream lag. * @type {number || null} */ this.LocalTs = null; /** * Video elapsed time in milliseconds. * @type {number || null} */ this.VideoTs = null; /** * Audio elapsed time in milliseconds. * @type {number || null} */ this.AudioTs = null; /** * Video bitrate in `metadata` in Kbps. * @type {number || null} */ this.MetaVideoRate = null; /** * Audio bitrate in `metadata` in Kbps. * @type {number || null} */ this.MetaAudioRate = null; /** * Frame rate in `metadata`. * @type {number || null} */ this.MateFps = null; /** * Push parameter * @type {string || null} */ this.StreamParam = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.PushDomain = 'PushDomain' in params ? params.PushDomain : null; this.AppName = 'AppName' in params ? params.AppName : null; this.ClientIp = 'ClientIp' in params ? params.ClientIp : null; this.BeginPushTime = 'BeginPushTime' in params ? params.BeginPushTime : null; this.Resolution = 'Resolution' in params ? params.Resolution : null; this.VCodec = 'VCodec' in params ? params.VCodec : null; this.ACodec = 'ACodec' in params ? params.ACodec : null; this.Sequence = 'Sequence' in params ? params.Sequence : null; this.VideoFps = 'VideoFps' in params ? params.VideoFps : null; this.VideoRate = 'VideoRate' in params ? params.VideoRate : null; this.AudioFps = 'AudioFps' in params ? params.AudioFps : null; this.AudioRate = 'AudioRate' in params ? params.AudioRate : null; this.LocalTs = 'LocalTs' in params ? params.LocalTs : null; this.VideoTs = 'VideoTs' in params ? params.VideoTs : null; this.AudioTs = 'AudioTs' in params ? params.AudioTs : null; this.MetaVideoRate = 'MetaVideoRate' in params ? params.MetaVideoRate : null; this.MetaAudioRate = 'MetaAudioRate' in params ? params.MetaAudioRate : null; this.MateFps = 'MateFps' in params ? params.MateFps : null; this.StreamParam = 'StreamParam' in params ? params.StreamParam : null; } }
JavaScript
class DomainCertInfo extends AbstractModel { constructor(){ super(); /** * Certificate ID. * @type {number || null} */ this.CertId = null; /** * Certificate name. * @type {string || null} */ this.CertName = null; /** * Description. * @type {string || null} */ this.Description = null; /** * Creation time in UTC format. * @type {string || null} */ this.CreateTime = null; /** * Certificate content. * @type {string || null} */ this.HttpsCrt = null; /** * Certificate type. 0: user-added certificate 1: Tencent Cloud-hosted certificate. * @type {number || null} */ this.CertType = null; /** * Certificate expiration time in UTC format. * @type {string || null} */ this.CertExpireTime = null; /** * Domain name that uses this certificate. * @type {string || null} */ this.DomainName = null; /** * Certificate status. * @type {number || null} */ this.Status = null; /** * List of domain names in the certificate. ["*.x.com"] for example. Note: this field may return `null`, indicating that no valid values can be obtained. * @type {Array.<string> || null} */ this.CertDomains = null; /** * Tencent Cloud SSL certificate ID. Note: this field may return `null`, indicating that no valid values can be obtained. * @type {string || null} */ this.CloudCertId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CertId = 'CertId' in params ? params.CertId : null; this.CertName = 'CertName' in params ? params.CertName : null; this.Description = 'Description' in params ? params.Description : null; this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.HttpsCrt = 'HttpsCrt' in params ? params.HttpsCrt : null; this.CertType = 'CertType' in params ? params.CertType : null; this.CertExpireTime = 'CertExpireTime' in params ? params.CertExpireTime : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.Status = 'Status' in params ? params.Status : null; this.CertDomains = 'CertDomains' in params ? params.CertDomains : null; this.CloudCertId = 'CloudCertId' in params ? params.CloudCertId : null; } }
JavaScript
class RecordTemplateInfo extends AbstractModel { constructor(){ super(); /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Template name. * @type {string || null} */ this.TemplateName = null; /** * Message description * @type {string || null} */ this.Description = null; /** * FLV recording parameter. * @type {RecordParam || null} */ this.FlvParam = null; /** * HLS recording parameter. * @type {RecordParam || null} */ this.HlsParam = null; /** * MP4 recording parameter. * @type {RecordParam || null} */ this.Mp4Param = null; /** * AAC recording parameter. * @type {RecordParam || null} */ this.AacParam = null; /** * 0: LVB, 1: LCB. * @type {number || null} */ this.IsDelayLive = null; /** * Custom HLS recording parameter * @type {HlsSpecialParam || null} */ this.HlsSpecialParam = null; /** * MP3 recording parameter. * @type {RecordParam || null} */ this.Mp3Param = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.TemplateName = 'TemplateName' in params ? params.TemplateName : null; this.Description = 'Description' in params ? params.Description : null; if (params.FlvParam) { let obj = new RecordParam(); obj.deserialize(params.FlvParam) this.FlvParam = obj; } if (params.HlsParam) { let obj = new RecordParam(); obj.deserialize(params.HlsParam) this.HlsParam = obj; } if (params.Mp4Param) { let obj = new RecordParam(); obj.deserialize(params.Mp4Param) this.Mp4Param = obj; } if (params.AacParam) { let obj = new RecordParam(); obj.deserialize(params.AacParam) this.AacParam = obj; } this.IsDelayLive = 'IsDelayLive' in params ? params.IsDelayLive : null; if (params.HlsSpecialParam) { let obj = new HlsSpecialParam(); obj.deserialize(params.HlsSpecialParam) this.HlsSpecialParam = obj; } if (params.Mp3Param) { let obj = new RecordParam(); obj.deserialize(params.Mp3Param) this.Mp3Param = obj; } } }
JavaScript
class ConcurrentRecordStreamNum extends AbstractModel { constructor(){ super(); /** * Time point. * @type {string || null} */ this.Time = null; /** * Number of channels. * @type {number || null} */ this.Num = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Num = 'Num' in params ? params.Num : null; } }
JavaScript
class DomainInfo extends AbstractModel { constructor(){ super(); /** * LVB domain name. * @type {string || null} */ this.Name = null; /** * Domain name type: 0: push. 1: playback. * @type {number || null} */ this.Type = null; /** * Domain name status: 0: deactivated. 1: activated. * @type {number || null} */ this.Status = null; /** * Creation time. * @type {string || null} */ this.CreateTime = null; /** * Whether there is a CNAME record pointing to a fixed rule domain name: 0: no. 1: yes. * @type {number || null} */ this.BCName = null; /** * Domain name corresponding to CNAME record. * @type {string || null} */ this.TargetDomain = null; /** * Playback region. This parameter is valid only if `Type` is 1. 1: in Mainland China. 2: global. 3: outside Mainland China. * @type {number || null} */ this.PlayType = null; /** * Whether it is LCB: 0: LVB. 1: LCB. * @type {number || null} */ this.IsDelayLive = null; /** * Information of currently used CNAME record. * @type {string || null} */ this.CurrentCName = null; /** * Disused parameter, which can be ignored. * @type {number || null} */ this.RentTag = null; /** * Disused parameter, which can be ignored. * @type {string || null} */ this.RentExpireTime = null; /** * 0: LVB. 1: LVB on Mini Program. Note: this field may return null, indicating that no valid values can be obtained. * @type {number || null} */ this.IsMiniProgramLive = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Name = 'Name' in params ? params.Name : null; this.Type = 'Type' in params ? params.Type : null; this.Status = 'Status' in params ? params.Status : null; this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.BCName = 'BCName' in params ? params.BCName : null; this.TargetDomain = 'TargetDomain' in params ? params.TargetDomain : null; this.PlayType = 'PlayType' in params ? params.PlayType : null; this.IsDelayLive = 'IsDelayLive' in params ? params.IsDelayLive : null; this.CurrentCName = 'CurrentCName' in params ? params.CurrentCName : null; this.RentTag = 'RentTag' in params ? params.RentTag : null; this.RentExpireTime = 'RentExpireTime' in params ? params.RentExpireTime : null; this.IsMiniProgramLive = 'IsMiniProgramLive' in params ? params.IsMiniProgramLive : null; } }
JavaScript
class CommonMixOutputParams extends AbstractModel { constructor(){ super(); /** * Output stream name. * @type {string || null} */ this.OutputStreamName = null; /** * Output stream type. Valid values: [0,1]. If this parameter is left empty, 0 will be used by default. If the output stream is a stream in the input stream list, enter 0. If you want the stream mix result to be a new stream, enter 1. If this value is 1, `output_stream_id` cannot appear in `input_stram_list`, and there cannot be a stream with the same ID on the LVB backend. * @type {number || null} */ this.OutputStreamType = null; /** * Output stream bitrate. Value range: [1,50000]. If this parameter is left empty, the system will automatically determine. * @type {number || null} */ this.OutputStreamBitRate = null; /** * Output stream GOP size. Value range: [1,10]. If this parameter is left empty, the system will automatically determine. * @type {number || null} */ this.OutputStreamGop = null; /** * Output stream frame rate. Value range: [1,60]. If this parameter is left empty, the system will automatically determine. * @type {number || null} */ this.OutputStreamFrameRate = null; /** * Output stream audio bitrate. Value range: [1,500] If this parameter is left empty, the system will automatically determine. * @type {number || null} */ this.OutputAudioBitRate = null; /** * Output stream audio sample rate. Valid values: [96000, 88200, 64000, 48000, 44100, 32000,24000, 22050, 16000, 12000, 11025, 8000]. If this parameter is left empty, the system will automatically determine. * @type {number || null} */ this.OutputAudioSampleRate = null; /** * Output stream audio sound channel. Valid values: [1,2]. If this parameter is left empty, the system will automatically determine. * @type {number || null} */ this.OutputAudioChannels = null; /** * SEI information in output stream. If there are no special needs, leave it empty. * @type {string || null} */ this.MixSei = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.OutputStreamName = 'OutputStreamName' in params ? params.OutputStreamName : null; this.OutputStreamType = 'OutputStreamType' in params ? params.OutputStreamType : null; this.OutputStreamBitRate = 'OutputStreamBitRate' in params ? params.OutputStreamBitRate : null; this.OutputStreamGop = 'OutputStreamGop' in params ? params.OutputStreamGop : null; this.OutputStreamFrameRate = 'OutputStreamFrameRate' in params ? params.OutputStreamFrameRate : null; this.OutputAudioBitRate = 'OutputAudioBitRate' in params ? params.OutputAudioBitRate : null; this.OutputAudioSampleRate = 'OutputAudioSampleRate' in params ? params.OutputAudioSampleRate : null; this.OutputAudioChannels = 'OutputAudioChannels' in params ? params.OutputAudioChannels : null; this.MixSei = 'MixSei' in params ? params.MixSei : null; } }
JavaScript
class PlayCodeTotalInfo extends AbstractModel { constructor(){ super(); /** * HTTP code. Valid values: 400, 403, 404, 500, 502, 503, 504. * @type {string || null} */ this.Code = null; /** * Total occurrences. * @type {number || null} */ this.Num = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Code = 'Code' in params ? params.Code : null; this.Num = 'Num' in params ? params.Num : null; } }
JavaScript
class BillCountryInfo extends AbstractModel { constructor(){ super(); /** * Country * @type {string || null} */ this.Name = null; /** * Detailed bandwidth information * @type {Array.<BillDataInfo> || null} */ this.BandInfoList = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Name = 'Name' in params ? params.Name : null; if (params.BandInfoList) { this.BandInfoList = new Array(); for (let z in params.BandInfoList) { let obj = new BillDataInfo(); obj.deserialize(params.BandInfoList[z]); this.BandInfoList.push(obj); } } } }
JavaScript
class ProIspPlayCodeDataInfo extends AbstractModel { constructor(){ super(); /** * Country or region. * @type {string || null} */ this.CountryAreaName = null; /** * District. * @type {string || null} */ this.ProvinceName = null; /** * ISP. * @type {string || null} */ this.IspName = null; /** * Occurrences of 2xx error codes. * @type {number || null} */ this.Code2xx = null; /** * Occurrences of 3xx error codes. * @type {number || null} */ this.Code3xx = null; /** * Occurrences of 4xx error codes. * @type {number || null} */ this.Code4xx = null; /** * Occurrences of 5xx error codes. * @type {number || null} */ this.Code5xx = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CountryAreaName = 'CountryAreaName' in params ? params.CountryAreaName : null; this.ProvinceName = 'ProvinceName' in params ? params.ProvinceName : null; this.IspName = 'IspName' in params ? params.IspName : null; this.Code2xx = 'Code2xx' in params ? params.Code2xx : null; this.Code3xx = 'Code3xx' in params ? params.Code3xx : null; this.Code4xx = 'Code4xx' in params ? params.Code4xx : null; this.Code5xx = 'Code5xx' in params ? params.Code5xx : null; } }
JavaScript
class CommonMixLayoutParams extends AbstractModel { constructor(){ super(); /** * Input layer. Value range: [1,16]. 1) For `image_layer` of background stream (i.e., main host video image or canvas), enter 1. 2) For audio stream mix, this parameter is also required. * @type {number || null} */ this.ImageLayer = null; /** * Input type. Value range: [0,5]. If this parameter is left empty, 0 will be used by default. 0: the input stream is audio/video. 2: the input stream is image. 3: the input stream is canvas. 4: the input stream is audio. 5: the input stream is pure video. * @type {number || null} */ this.InputType = null; /** * Output width of input video image. Value range: Pixel: [0,2000] Percentage: [0.01,0.99] If this parameter is left empty, the input stream width will be used by default. If percentage is used, the expected output is (percentage * background width). * @type {number || null} */ this.ImageWidth = null; /** * Output height of input video image. Value range: Pixel: [0,2000] Percentage: [0.01,0.99] If this parameter is left empty, the input stream height will be used by default. If percentage is used, the expected output is (percentage * background height). * @type {number || null} */ this.ImageHeight = null; /** * X-axis offset of input in output video image. Value range: Pixel: [0,2000] Percentage: [0.01,0.99] If this parameter is left empty, 0 will be used by default. Horizontal offset from the top-left corner of main host background video image. If percentage is used, the expected output is (percentage * background width). * @type {number || null} */ this.LocationX = null; /** * Y-axis offset of input in output video image. Value range: Pixel: [0,2000] Percentage: [0.01,0.99] If this parameter is left empty, 0 will be used by default. Vertical offset from the top-left corner of main host background video image. If percentage is used, the expected output is (percentage * background width) * @type {number || null} */ this.LocationY = null; /** * When `InputType` is 3 (canvas), this value indicates the canvas color. Commonly used colors include: Red: 0xcc0033. Yellow: 0xcc9900. Green: 0xcccc33. Blue: 0x99CCFF. Black: 0x000000. White: 0xFFFFFF. Gray: 0x999999 * @type {string || null} */ this.Color = null; /** * When `InputType` is 2 (image), this value is the watermark ID. * @type {number || null} */ this.WatermarkId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.ImageLayer = 'ImageLayer' in params ? params.ImageLayer : null; this.InputType = 'InputType' in params ? params.InputType : null; this.ImageWidth = 'ImageWidth' in params ? params.ImageWidth : null; this.ImageHeight = 'ImageHeight' in params ? params.ImageHeight : null; this.LocationX = 'LocationX' in params ? params.LocationX : null; this.LocationY = 'LocationY' in params ? params.LocationY : null; this.Color = 'Color' in params ? params.Color : null; this.WatermarkId = 'WatermarkId' in params ? params.WatermarkId : null; } }
JavaScript
class CallBackTemplateInfo extends AbstractModel { constructor(){ super(); /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Template name. * @type {string || null} */ this.TemplateName = null; /** * Description. * @type {string || null} */ this.Description = null; /** * Stream starting callback URL. * @type {string || null} */ this.StreamBeginNotifyUrl = null; /** * Stream mixing callback URL (disused) * @type {string || null} */ this.StreamMixNotifyUrl = null; /** * Interruption callback URL. * @type {string || null} */ this.StreamEndNotifyUrl = null; /** * Recording callback URL. * @type {string || null} */ this.RecordNotifyUrl = null; /** * Screencapturing callback URL. * @type {string || null} */ this.SnapshotNotifyUrl = null; /** * Porn detection callback URL. * @type {string || null} */ this.PornCensorshipNotifyUrl = null; /** * Callback authentication key. * @type {string || null} */ this.CallbackKey = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.TemplateName = 'TemplateName' in params ? params.TemplateName : null; this.Description = 'Description' in params ? params.Description : null; this.StreamBeginNotifyUrl = 'StreamBeginNotifyUrl' in params ? params.StreamBeginNotifyUrl : null; this.StreamMixNotifyUrl = 'StreamMixNotifyUrl' in params ? params.StreamMixNotifyUrl : null; this.StreamEndNotifyUrl = 'StreamEndNotifyUrl' in params ? params.StreamEndNotifyUrl : null; this.RecordNotifyUrl = 'RecordNotifyUrl' in params ? params.RecordNotifyUrl : null; this.SnapshotNotifyUrl = 'SnapshotNotifyUrl' in params ? params.SnapshotNotifyUrl : null; this.PornCensorshipNotifyUrl = 'PornCensorshipNotifyUrl' in params ? params.PornCensorshipNotifyUrl : null; this.CallbackKey = 'CallbackKey' in params ? params.CallbackKey : null; } }
JavaScript
class TimeValue extends AbstractModel { constructor(){ super(); /** * UTC time in the format of `yyyy-mm-ddTHH:MM:SSZ`. * @type {string || null} */ this.Time = null; /** * Value. * @type {number || null} */ this.Num = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Num = 'Num' in params ? params.Num : null; } }
JavaScript
class StreamOnlineInfo extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Push time list * @type {Array.<PublishTime> || null} */ this.PublishTimeList = null; /** * Application name. * @type {string || null} */ this.AppName = null; /** * Push domain name. * @type {string || null} */ this.DomainName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; if (params.PublishTimeList) { this.PublishTimeList = new Array(); for (let z in params.PublishTimeList) { let obj = new PublishTime(); obj.deserialize(params.PublishTimeList[z]); this.PublishTimeList.push(obj); } } this.AppName = 'AppName' in params ? params.AppName : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; } }
JavaScript
class RuleInfo extends AbstractModel { constructor(){ super(); /** * Rule creation time. * @type {string || null} */ this.CreateTime = null; /** * Rule update time. * @type {string || null} */ this.UpdateTime = null; /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Push path. * @type {string || null} */ this.AppName = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.UpdateTime = 'UpdateTime' in params ? params.UpdateTime : null; this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; } }
JavaScript
class BillAreaInfo extends AbstractModel { constructor(){ super(); /** * Region name * @type {string || null} */ this.Name = null; /** * Detailed country information * @type {Array.<BillCountryInfo> || null} */ this.Countrys = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Name = 'Name' in params ? params.Name : null; if (params.Countrys) { this.Countrys = new Array(); for (let z in params.Countrys) { let obj = new BillCountryInfo(); obj.deserialize(params.Countrys[z]); this.Countrys.push(obj); } } } }
JavaScript
class PlayDataInfoByStream extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Total traffic in MB. * @type {number || null} */ this.TotalFlux = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.TotalFlux = 'TotalFlux' in params ? params.TotalFlux : null; } }
JavaScript
class DayStreamPlayInfo extends AbstractModel { constructor(){ super(); /** * Data point in time in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.Time = null; /** * Bandwidth in Mbps. * @type {number || null} */ this.Bandwidth = null; /** * Traffic in MB. * @type {number || null} */ this.Flux = null; /** * Number of requests. * @type {number || null} */ this.Request = null; /** * Number of online viewers. * @type {number || null} */ this.Online = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null; this.Flux = 'Flux' in params ? params.Flux : null; this.Request = 'Request' in params ? params.Request : null; this.Online = 'Online' in params ? params.Online : null; } }
JavaScript
class CommonMixInputParam extends AbstractModel { constructor(){ super(); /** * Input stream name, which can contain up to 80 bytes of letters, digits, and underscores. The value should be the name of an input stream for stream mix when `LayoutParams.InputType` is set to `0` (audio and video), `4` (pure audio), or `5` (pure video). The value can be a random name for identification, such as `Canvas1` or `Picture1`, when `LayoutParams.InputType` is set to `2` (image) or `3` (canvas). * @type {string || null} */ this.InputStreamName = null; /** * Input stream layout parameter. * @type {CommonMixLayoutParams || null} */ this.LayoutParams = null; /** * Input stream crop parameter. * @type {CommonMixCropParams || null} */ this.CropParams = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.InputStreamName = 'InputStreamName' in params ? params.InputStreamName : null; if (params.LayoutParams) { let obj = new CommonMixLayoutParams(); obj.deserialize(params.LayoutParams) this.LayoutParams = obj; } if (params.CropParams) { let obj = new CommonMixCropParams(); obj.deserialize(params.CropParams) this.CropParams = obj; } } }
JavaScript
class StreamEventInfo extends AbstractModel { constructor(){ super(); /** * Application name. * @type {string || null} */ this.AppName = null; /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Push start time. In UTC format, such as 2019-01-07T12:00:00Z. * @type {string || null} */ this.StreamStartTime = null; /** * Push end time. In UTC format, such as 2019-01-07T15:00:00Z. * @type {string || null} */ this.StreamEndTime = null; /** * Stop reason. * @type {string || null} */ this.StopReason = null; /** * Push duration in seconds. * @type {number || null} */ this.Duration = null; /** * Host IP. * @type {string || null} */ this.ClientIp = null; /** * Resolution. * @type {string || null} */ this.Resolution = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.AppName = 'AppName' in params ? params.AppName : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; this.StreamStartTime = 'StreamStartTime' in params ? params.StreamStartTime : null; this.StreamEndTime = 'StreamEndTime' in params ? params.StreamEndTime : null; this.StopReason = 'StopReason' in params ? params.StopReason : null; this.Duration = 'Duration' in params ? params.Duration : null; this.ClientIp = 'ClientIp' in params ? params.ClientIp : null; this.Resolution = 'Resolution' in params ? params.Resolution : null; } }
JavaScript
class RefererAuthConfig extends AbstractModel { constructor(){ super(); /** * Domain name * @type {string || null} */ this.DomainName = null; /** * Whether to enable referer. Valid values: `0` (no), `1` (yes) * @type {number || null} */ this.Enable = null; /** * List type. Valid values: `0` (blocklist), `1` (allowlist) * @type {number || null} */ this.Type = null; /** * Whether to allow empty referer. Valid values: `0` (no), `1` (yes) * @type {number || null} */ this.AllowEmpty = null; /** * Referer list. Separate items in it with semicolons (;). * @type {string || null} */ this.Rules = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.Enable = 'Enable' in params ? params.Enable : null; this.Type = 'Type' in params ? params.Type : null; this.AllowEmpty = 'AllowEmpty' in params ? params.AllowEmpty : null; this.Rules = 'Rules' in params ? params.Rules : null; } }
JavaScript
class PushDataInfo extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Push path. * @type {string || null} */ this.AppName = null; /** * Push client IP. * @type {string || null} */ this.ClientIp = null; /** * IP of the server that receives the stream. * @type {string || null} */ this.ServerIp = null; /** * Pushed video frame rate in Hz. * @type {number || null} */ this.VideoFps = null; /** * Pushed video bitrate in bps. * @type {number || null} */ this.VideoSpeed = null; /** * Pushed audio frame rate in Hz. * @type {number || null} */ this.AudioFps = null; /** * Pushed audio bitrate in bps. * @type {number || null} */ this.AudioSpeed = null; /** * Push domain name. * @type {string || null} */ this.PushDomain = null; /** * Push start time. * @type {string || null} */ this.BeginPushTime = null; /** * Audio codec, Example: AAC. * @type {string || null} */ this.Acodec = null; /** * Video codec, Example: H.264. * @type {string || null} */ this.Vcodec = null; /** * Resolution. * @type {string || null} */ this.Resolution = null; /** * Sample rate. * @type {number || null} */ this.AsampleRate = null; /** * Audio bitrate in `metadata` in Kbps. * @type {number || null} */ this.MetaAudioSpeed = null; /** * Video bitrate in `metadata` in Kbps. * @type {number || null} */ this.MetaVideoSpeed = null; /** * Frame rate in `metadata`. * @type {number || null} */ this.MetaFps = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.ClientIp = 'ClientIp' in params ? params.ClientIp : null; this.ServerIp = 'ServerIp' in params ? params.ServerIp : null; this.VideoFps = 'VideoFps' in params ? params.VideoFps : null; this.VideoSpeed = 'VideoSpeed' in params ? params.VideoSpeed : null; this.AudioFps = 'AudioFps' in params ? params.AudioFps : null; this.AudioSpeed = 'AudioSpeed' in params ? params.AudioSpeed : null; this.PushDomain = 'PushDomain' in params ? params.PushDomain : null; this.BeginPushTime = 'BeginPushTime' in params ? params.BeginPushTime : null; this.Acodec = 'Acodec' in params ? params.Acodec : null; this.Vcodec = 'Vcodec' in params ? params.Vcodec : null; this.Resolution = 'Resolution' in params ? params.Resolution : null; this.AsampleRate = 'AsampleRate' in params ? params.AsampleRate : null; this.MetaAudioSpeed = 'MetaAudioSpeed' in params ? params.MetaAudioSpeed : null; this.MetaVideoSpeed = 'MetaVideoSpeed' in params ? params.MetaVideoSpeed : null; this.MetaFps = 'MetaFps' in params ? params.MetaFps : null; } }
JavaScript
class TranscodeDetailInfo extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Start time (Beijing time) in the format of `yyyy-mm-dd HH:MM`. * @type {string || null} */ this.StartTime = null; /** * End time (Beijing time) in the format of `yyyy-mm-dd HH:MM`. * @type {string || null} */ this.EndTime = null; /** * Transcoding duration in minutes. Note: given the possible interruptions during push, duration here is the sum of actual duration of transcoding instead of the interval between the start time and end time. * @type {number || null} */ this.Duration = null; /** * Codec with modules, Example: liveprocessor_H264: LVB transcoding - H264, liveprocessor_H265: LVB transcoding - H265, topspeed_H264: top speed codec - H264, topspeed_H265: top speed codec - H265. * @type {string || null} */ this.ModuleCodec = null; /** * Bitrate. * @type {number || null} */ this.Bitrate = null; /** * Type. Valid values: Transcode, MixStream, WaterMark. * @type {string || null} */ this.Type = null; /** * Push domain name. * @type {string || null} */ this.PushDomain = null; /** * Resolution. * @type {string || null} */ this.Resolution = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.StartTime = 'StartTime' in params ? params.StartTime : null; this.EndTime = 'EndTime' in params ? params.EndTime : null; this.Duration = 'Duration' in params ? params.Duration : null; this.ModuleCodec = 'ModuleCodec' in params ? params.ModuleCodec : null; this.Bitrate = 'Bitrate' in params ? params.Bitrate : null; this.Type = 'Type' in params ? params.Type : null; this.PushDomain = 'PushDomain' in params ? params.PushDomain : null; this.Resolution = 'Resolution' in params ? params.Resolution : null; } }
JavaScript
class StreamName extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Application name. * @type {string || null} */ this.AppName = null; /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Push start time. In UTC format, such as 2019-01-07T12:00:00Z. * @type {string || null} */ this.StreamStartTime = null; /** * Push end time. In UTC format, such as 2019-01-07T15:00:00Z. * @type {string || null} */ this.StreamEndTime = null; /** * Stop reason. * @type {string || null} */ this.StopReason = null; /** * Push duration in seconds. * @type {number || null} */ this.Duration = null; /** * Host IP. * @type {string || null} */ this.ClientIp = null; /** * Resolution. * @type {string || null} */ this.Resolution = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.StreamStartTime = 'StreamStartTime' in params ? params.StreamStartTime : null; this.StreamEndTime = 'StreamEndTime' in params ? params.StreamEndTime : null; this.StopReason = 'StopReason' in params ? params.StopReason : null; this.Duration = 'Duration' in params ? params.Duration : null; this.ClientIp = 'ClientIp' in params ? params.ClientIp : null; this.Resolution = 'Resolution' in params ? params.Resolution : null; } }
JavaScript
class CdnPlayStatData extends AbstractModel { constructor(){ super(); /** * Time point in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.Time = null; /** * Bandwidth in Mbps. * @type {number || null} */ this.Bandwidth = null; /** * Traffic in MB. * @type {number || null} */ this.Flux = null; /** * Number of new requests. * @type {number || null} */ this.Request = null; /** * Number of concurrent connections. * @type {number || null} */ this.Online = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null; this.Flux = 'Flux' in params ? params.Flux : null; this.Request = 'Request' in params ? params.Request : null; this.Online = 'Online' in params ? params.Online : null; } }
JavaScript
class DomainInfoList extends AbstractModel { constructor(){ super(); /** * Domain name. * @type {string || null} */ this.Domain = null; /** * Details. * @type {Array.<DomainDetailInfo> || null} */ this.DetailInfoList = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Domain = 'Domain' in params ? params.Domain : null; if (params.DetailInfoList) { this.DetailInfoList = new Array(); for (let z in params.DetailInfoList) { let obj = new DomainDetailInfo(); obj.deserialize(params.DetailInfoList[z]); this.DetailInfoList.push(obj); } } } }
JavaScript
class WatermarkInfo extends AbstractModel { constructor(){ super(); /** * Watermark ID. * @type {number || null} */ this.WatermarkId = null; /** * Watermark image URL. * @type {string || null} */ this.PictureUrl = null; /** * Display position: X-axis offset. * @type {number || null} */ this.XPosition = null; /** * Display position: Y-axis offset. * @type {number || null} */ this.YPosition = null; /** * Watermark name. * @type {string || null} */ this.WatermarkName = null; /** * Current status. 0: not used. 1: in use. * @type {number || null} */ this.Status = null; /** * Creation time. * @type {string || null} */ this.CreateTime = null; /** * Watermark width. * @type {number || null} */ this.Width = null; /** * Watermark height. * @type {number || null} */ this.Height = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.WatermarkId = 'WatermarkId' in params ? params.WatermarkId : null; this.PictureUrl = 'PictureUrl' in params ? params.PictureUrl : null; this.XPosition = 'XPosition' in params ? params.XPosition : null; this.YPosition = 'YPosition' in params ? params.YPosition : null; this.WatermarkName = 'WatermarkName' in params ? params.WatermarkName : null; this.Status = 'Status' in params ? params.Status : null; this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.Width = 'Width' in params ? params.Width : null; this.Height = 'Height' in params ? params.Height : null; } }
JavaScript
class PublishTime extends AbstractModel { constructor(){ super(); /** * Push time. In UTC format, such as 2018-06-29T19:00:00Z. * @type {string || null} */ this.PublishTime = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.PublishTime = 'PublishTime' in params ? params.PublishTime : null; } }
JavaScript
class MonitorStreamPlayInfo extends AbstractModel { constructor(){ super(); /** * Playback domain name. * @type {string || null} */ this.PlayDomain = null; /** * Stream ID. * @type {string || null} */ this.StreamName = null; /** * Playback bitrate. 0 indicates the original bitrate. * @type {number || null} */ this.Rate = null; /** * Playback protocol. Valid values: Unknown, Flv, Hls, Rtmp, Huyap2p. * @type {string || null} */ this.Protocol = null; /** * Bandwidth in Mbps. * @type {number || null} */ this.Bandwidth = null; /** * Number of online viewers. A data point is sampled per minute, and the number of TCP connections across the sample points is calculated. * @type {number || null} */ this.Online = null; /** * Number of requests. * @type {number || null} */ this.Request = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.PlayDomain = 'PlayDomain' in params ? params.PlayDomain : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; this.Rate = 'Rate' in params ? params.Rate : null; this.Protocol = 'Protocol' in params ? params.Protocol : null; this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null; this.Online = 'Online' in params ? params.Online : null; this.Request = 'Request' in params ? params.Request : null; } }
JavaScript
class ProIspPlaySumInfo extends AbstractModel { constructor(){ super(); /** * District/ISP/country/region. * @type {string || null} */ this.Name = null; /** * Total traffic in MB. * @type {number || null} */ this.TotalFlux = null; /** * Total number of requests. * @type {number || null} */ this.TotalRequest = null; /** * Average download traffic in MB/s. * @type {number || null} */ this.AvgFluxPerSecond = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Name = 'Name' in params ? params.Name : null; this.TotalFlux = 'TotalFlux' in params ? params.TotalFlux : null; this.TotalRequest = 'TotalRequest' in params ? params.TotalRequest : null; this.AvgFluxPerSecond = 'AvgFluxPerSecond' in params ? params.AvgFluxPerSecond : null; } }
JavaScript
class SnapshotTemplateInfo extends AbstractModel { constructor(){ super(); /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Template name. * @type {string || null} */ this.TemplateName = null; /** * Screencapturing interval. Value range: 5-300s. * @type {number || null} */ this.SnapshotInterval = null; /** * Screenshot width. Value range: 0-3000. 0: original width and fit to the original ratio. * @type {number || null} */ this.Width = null; /** * Screenshot height. Value range: 0-2000. 0: original height and fit to the original ratio. * @type {number || null} */ this.Height = null; /** * Whether to enable porn detection. 0: no, 1: yes. * @type {number || null} */ this.PornFlag = null; /** * COS application ID. * @type {number || null} */ this.CosAppId = null; /** * COS bucket name. * @type {string || null} */ this.CosBucket = null; /** * COS region. * @type {string || null} */ this.CosRegion = null; /** * Template description. * @type {string || null} */ this.Description = null; /** * COS bucket folder prefix. Note: this field may return null, indicating that no valid values can be obtained. * @type {string || null} */ this.CosPrefix = null; /** * COS filename. Note: this field may return null, indicating that no valid values can be obtained. * @type {string || null} */ this.CosFileName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.TemplateName = 'TemplateName' in params ? params.TemplateName : null; this.SnapshotInterval = 'SnapshotInterval' in params ? params.SnapshotInterval : null; this.Width = 'Width' in params ? params.Width : null; this.Height = 'Height' in params ? params.Height : null; this.PornFlag = 'PornFlag' in params ? params.PornFlag : null; this.CosAppId = 'CosAppId' in params ? params.CosAppId : null; this.CosBucket = 'CosBucket' in params ? params.CosBucket : null; this.CosRegion = 'CosRegion' in params ? params.CosRegion : null; this.Description = 'Description' in params ? params.Description : null; this.CosPrefix = 'CosPrefix' in params ? params.CosPrefix : null; this.CosFileName = 'CosFileName' in params ? params.CosFileName : null; } }
JavaScript
class BandwidthInfo extends AbstractModel { constructor(){ super(); /** * Format of return value: yyyy-mm-dd HH:MM:SS The time accuracy matches with the query granularity. * @type {string || null} */ this.Time = null; /** * Bandwidth. * @type {number || null} */ this.Bandwidth = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null; } }
JavaScript
class CertInfo extends AbstractModel { constructor(){ super(); /** * Certificate ID. * @type {number || null} */ this.CertId = null; /** * Certificate name. * @type {string || null} */ this.CertName = null; /** * Description. * @type {string || null} */ this.Description = null; /** * Creation time in UTC format. * @type {string || null} */ this.CreateTime = null; /** * Certificate content. * @type {string || null} */ this.HttpsCrt = null; /** * Certificate type. 0: user-added certificate 1: Tencent Cloud-hosted certificate * @type {number || null} */ this.CertType = null; /** * Certificate expiration time in UTC format. * @type {string || null} */ this.CertExpireTime = null; /** * List of domain names that use this certificate. * @type {Array.<string> || null} */ this.DomainList = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CertId = 'CertId' in params ? params.CertId : null; this.CertName = 'CertName' in params ? params.CertName : null; this.Description = 'Description' in params ? params.Description : null; this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.HttpsCrt = 'HttpsCrt' in params ? params.HttpsCrt : null; this.CertType = 'CertType' in params ? params.CertType : null; this.CertExpireTime = 'CertExpireTime' in params ? params.CertExpireTime : null; this.DomainList = 'DomainList' in params ? params.DomainList : null; } }
JavaScript
class ClientIpPlaySumInfo extends AbstractModel { constructor(){ super(); /** * Client IP in dotted-decimal notation. * @type {string || null} */ this.ClientIp = null; /** * District where the client is located. * @type {string || null} */ this.Province = null; /** * Total traffic. * @type {number || null} */ this.TotalFlux = null; /** * Total number of requests. * @type {number || null} */ this.TotalRequest = null; /** * Total number of failed requests. * @type {number || null} */ this.TotalFailedRequest = null; /** * Country/region where the client is located. * @type {string || null} */ this.CountryArea = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.ClientIp = 'ClientIp' in params ? params.ClientIp : null; this.Province = 'Province' in params ? params.Province : null; this.TotalFlux = 'TotalFlux' in params ? params.TotalFlux : null; this.TotalRequest = 'TotalRequest' in params ? params.TotalRequest : null; this.TotalFailedRequest = 'TotalFailedRequest' in params ? params.TotalFailedRequest : null; this.CountryArea = 'CountryArea' in params ? params.CountryArea : null; } }
JavaScript
class CommonMixControlParams extends AbstractModel { constructor(){ super(); /** * Value range: [0,1]. If 1 is entered, when the layer resolution in the parameter is different from the actual video resolution, the video will be automatically cropped according to the resolution set by the layer. * @type {number || null} */ this.UseMixCropCenter = null; /** * Value range: [0,1]. If this parameter is set to 1, when both `InputStreamList` and `OutputParams.OutputStreamType` are set to 1, you can copy a stream instead of canceling it. * @type {number || null} */ this.AllowCopy = null; /** * Valid values: 0, 1 If you set this parameter to 1, SEI (Supplemental Enhanced Information) of the input streams will be passed through. * @type {number || null} */ this.PassInputSei = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.UseMixCropCenter = 'UseMixCropCenter' in params ? params.UseMixCropCenter : null; this.AllowCopy = 'AllowCopy' in params ? params.AllowCopy : null; this.PassInputSei = 'PassInputSei' in params ? params.PassInputSei : null; } }
JavaScript
class RecordParam extends AbstractModel { constructor(){ super(); /** * Max recording time per file Default value: `1800` (seconds) Value range: 30-7200 This parameter is invalid for HLS. Only one HLS file will be generated from push start to push end. * @type {number || null} */ this.RecordInterval = null; /** * Storage duration of the recording file Value range: 0-129600000 seconds (0-1500 days) `0`: permanent * @type {number || null} */ this.StorageTime = null; /** * Whether to enable recording in the current format. Default value: 0. 0: no, 1: yes. * @type {number || null} */ this.Enable = null; /** * VOD subapplication ID. * @type {number || null} */ this.VodSubAppId = null; /** * Recording filename. Supported special placeholders include: {StreamID}: stream ID {StartYear}: start time - year {StartMonth}: start time - month {StartDay}: start time - day {StartHour}: start time - hour {StartMinute}: start time - minute {StartSecond}: start time - second {StartMillisecond}: start time - millisecond {EndYear}: end time - year {EndMonth}: end time - month {EndDay}: end time - day {EndHour}: end time - hour {EndMinute}: end time - minute {EndSecond}: end time - second {EndMillisecond}: end time - millisecond If this parameter is not set, the recording filename will be `{StreamID}_{StartYear}-{StartMonth}-{StartDay}-{StartHour}-{StartMinute}-{StartSecond}_{EndYear}-{EndMonth}-{EndDay}-{EndHour}-{EndMinute}-{EndSecond}` by default * @type {string || null} */ this.VodFileName = null; /** * Task flow Note: this field may return `null`, indicating that no valid value is obtained. * @type {string || null} */ this.Procedure = null; /** * Video storage class. Valid values: `normal`: STANDARD `cold`: STANDARD_IA Note: this field may return `null`, indicating that no valid value is obtained. * @type {string || null} */ this.StorageMode = null; /** * VOD subapplication category Note: this field may return `null`, indicating that no valid value is obtained. * @type {number || null} */ this.ClassId = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.RecordInterval = 'RecordInterval' in params ? params.RecordInterval : null; this.StorageTime = 'StorageTime' in params ? params.StorageTime : null; this.Enable = 'Enable' in params ? params.Enable : null; this.VodSubAppId = 'VodSubAppId' in params ? params.VodSubAppId : null; this.VodFileName = 'VodFileName' in params ? params.VodFileName : null; this.Procedure = 'Procedure' in params ? params.Procedure : null; this.StorageMode = 'StorageMode' in params ? params.StorageMode : null; this.ClassId = 'ClassId' in params ? params.ClassId : null; } }
JavaScript
class DomainDetailInfo extends AbstractModel { constructor(){ super(); /** * In or outside Mainland China: Mainland: data in Mainland China. Oversea: data outside Mainland China. * @type {string || null} */ this.MainlandOrOversea = null; /** * Bandwidth in Mbps. * @type {number || null} */ this.Bandwidth = null; /** * Traffic in MB. * @type {number || null} */ this.Flux = null; /** * Number of viewers. * @type {number || null} */ this.Online = null; /** * Number of requests. * @type {number || null} */ this.Request = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.MainlandOrOversea = 'MainlandOrOversea' in params ? params.MainlandOrOversea : null; this.Bandwidth = 'Bandwidth' in params ? params.Bandwidth : null; this.Flux = 'Flux' in params ? params.Flux : null; this.Online = 'Online' in params ? params.Online : null; this.Request = 'Request' in params ? params.Request : null; } }
JavaScript
class HttpStatusInfo extends AbstractModel { constructor(){ super(); /** * Playback HTTP status code. * @type {string || null} */ this.HttpStatus = null; /** * Quantity. * @type {number || null} */ this.Num = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.HttpStatus = 'HttpStatus' in params ? params.HttpStatus : null; this.Num = 'Num' in params ? params.Num : null; } }
JavaScript
class HttpStatusData extends AbstractModel { constructor(){ super(); /** * Data point in time, In the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.Time = null; /** * Playback status code details. * @type {Array.<HttpStatusInfo> || null} */ this.HttpStatusInfoList = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; if (params.HttpStatusInfoList) { this.HttpStatusInfoList = new Array(); for (let z in params.HttpStatusInfoList) { let obj = new HttpStatusInfo(); obj.deserialize(params.HttpStatusInfoList[z]); this.HttpStatusInfoList.push(obj); } } } }
JavaScript
class HttpCodeInfo extends AbstractModel { constructor(){ super(); /** * HTTP return code. Example: "2xx", "3xx", "4xx", "5xx". * @type {string || null} */ this.HttpCode = null; /** * Statistics. 0 will be added for points in time when there is no data. * @type {Array.<HttpCodeValue> || null} */ this.ValueList = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.HttpCode = 'HttpCode' in params ? params.HttpCode : null; if (params.ValueList) { this.ValueList = new Array(); for (let z in params.ValueList) { let obj = new HttpCodeValue(); obj.deserialize(params.ValueList[z]); this.ValueList.push(obj); } } } }
JavaScript
class PlayAuthKeyInfo extends AbstractModel { constructor(){ super(); /** * Domain name. * @type {string || null} */ this.DomainName = null; /** * Whether to enable: 0: disable. 1: enable. * @type {number || null} */ this.Enable = null; /** * Authentication key. * @type {string || null} */ this.AuthKey = null; /** * Validity period in seconds. * @type {number || null} */ this.AuthDelta = null; /** * Authentication `BackKey`. * @type {string || null} */ this.AuthBackKey = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.Enable = 'Enable' in params ? params.Enable : null; this.AuthKey = 'AuthKey' in params ? params.AuthKey : null; this.AuthDelta = 'AuthDelta' in params ? params.AuthDelta : null; this.AuthBackKey = 'AuthBackKey' in params ? params.AuthBackKey : null; } }
JavaScript
class CallBackRuleInfo extends AbstractModel { constructor(){ super(); /** * Rule creation time. * @type {string || null} */ this.CreateTime = null; /** * Rule update time. * @type {string || null} */ this.UpdateTime = null; /** * Template ID. * @type {number || null} */ this.TemplateId = null; /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Push path. * @type {string || null} */ this.AppName = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.UpdateTime = 'UpdateTime' in params ? params.UpdateTime : null; this.TemplateId = 'TemplateId' in params ? params.TemplateId : null; this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; } }
JavaScript
class PlaySumStatInfo extends AbstractModel { constructor(){ super(); /** * Domain name or stream ID. * @type {string || null} */ this.Name = null; /** * Average download speed, In MB/s. Calculation formula: average download speed per minute. * @type {number || null} */ this.AvgFluxPerSecond = null; /** * Total traffic in MB. * @type {number || null} */ this.TotalFlux = null; /** * Total number of requests. * @type {number || null} */ this.TotalRequest = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Name = 'Name' in params ? params.Name : null; this.AvgFluxPerSecond = 'AvgFluxPerSecond' in params ? params.AvgFluxPerSecond : null; this.TotalFlux = 'TotalFlux' in params ? params.TotalFlux : null; this.TotalRequest = 'TotalRequest' in params ? params.TotalRequest : null; } }
JavaScript
class HlsSpecialParam extends AbstractModel { constructor(){ super(); /** * Timeout period for restarting an interrupted HLS push. Value range: [0, 1,800]. * @type {number || null} */ this.FlowContinueDuration = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.FlowContinueDuration = 'FlowContinueDuration' in params ? params.FlowContinueDuration : null; } }
JavaScript
class HttpCodeValue extends AbstractModel { constructor(){ super(); /** * Time in the format of `yyyy-mm-dd HH:MM:SS`. * @type {string || null} */ this.Time = null; /** * Occurrences. * @type {number || null} */ this.Numbers = null; /** * Proportion. * @type {number || null} */ this.Percentage = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Numbers = 'Numbers' in params ? params.Numbers : null; this.Percentage = 'Percentage' in params ? params.Percentage : null; } }
JavaScript
class PlayStatInfo extends AbstractModel { constructor(){ super(); /** * Data point in time. * @type {string || null} */ this.Time = null; /** * Value of bandwidth/traffic/number of requests/number of concurrent connections/download speed. If there is no data returned, the value is 0. Note: this field may return null, indicating that no valid values can be obtained. * @type {number || null} */ this.Value = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.Time = 'Time' in params ? params.Time : null; this.Value = 'Value' in params ? params.Value : null; } }
JavaScript
class DelayInfo extends AbstractModel { constructor(){ super(); /** * Push domain name. * @type {string || null} */ this.DomainName = null; /** * Push path, which is the same as the `AppName` in push and playback addresses and is `live` by default. * @type {string || null} */ this.AppName = null; /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Delay time in seconds. * @type {number || null} */ this.DelayInterval = null; /** * Creation time in UTC time. Note: the difference between UTC time and Beijing time is 8 hours. Example: 2019-06-18T12:00:00Z (i.e., June 18, 2019 20:00:00 Beijing time). * @type {string || null} */ this.CreateTime = null; /** * Expiration time in UTC time. Note: the difference between UTC time and Beijing time is 8 hours. Example: 2019-06-18T12:00:00Z (i.e., June 18, 2019 20:00:00 Beijing time). * @type {string || null} */ this.ExpireTime = null; /** * Current status: -1: expired. 1: in effect. * @type {number || null} */ this.Status = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.DomainName = 'DomainName' in params ? params.DomainName : null; this.AppName = 'AppName' in params ? params.AppName : null; this.StreamName = 'StreamName' in params ? params.StreamName : null; this.DelayInterval = 'DelayInterval' in params ? params.DelayInterval : null; this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.ExpireTime = 'ExpireTime' in params ? params.ExpireTime : null; this.Status = 'Status' in params ? params.Status : null; } }
JavaScript
class ForbidStreamInfo extends AbstractModel { constructor(){ super(); /** * Stream name. * @type {string || null} */ this.StreamName = null; /** * Creation time. * @type {string || null} */ this.CreateTime = null; /** * Forbidding expiration time. * @type {string || null} */ this.ExpireTime = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.StreamName = 'StreamName' in params ? params.StreamName : null; this.CreateTime = 'CreateTime' in params ? params.CreateTime : null; this.ExpireTime = 'ExpireTime' in params ? params.ExpireTime : null; } }
JavaScript
class GroupProIspDataInfo extends AbstractModel { constructor(){ super(); /** * District. * @type {string || null} */ this.ProvinceName = null; /** * ISP. * @type {string || null} */ this.IspName = null; /** * Detailed data at the minute level. * @type {Array.<CdnPlayStatData> || null} */ this.DetailInfoList = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.ProvinceName = 'ProvinceName' in params ? params.ProvinceName : null; this.IspName = 'IspName' in params ? params.IspName : null; if (params.DetailInfoList) { this.DetailInfoList = new Array(); for (let z in params.DetailInfoList) { let obj = new CdnPlayStatData(); obj.deserialize(params.DetailInfoList[z]); this.DetailInfoList.push(obj); } } } }
JavaScript
class CommonMixCropParams extends AbstractModel { constructor(){ super(); /** * Crop width. Value range: [0,2000]. * @type {number || null} */ this.CropWidth = null; /** * Crop height. Value range: [0,2000]. * @type {number || null} */ this.CropHeight = null; /** * Starting crop X coordinate. Value range: [0,2000]. * @type {number || null} */ this.CropStartLocationX = null; /** * Starting crop Y coordinate. Value range: [0,2000]. * @type {number || null} */ this.CropStartLocationY = null; } /** * @private */ deserialize(params) { if (!params) { return; } this.CropWidth = 'CropWidth' in params ? params.CropWidth : null; this.CropHeight = 'CropHeight' in params ? params.CropHeight : null; this.CropStartLocationX = 'CropStartLocationX' in params ? params.CropStartLocationX : null; this.CropStartLocationY = 'CropStartLocationY' in params ? params.CropStartLocationY : null; } }
JavaScript
class DeviceMgrProvider { /** * The dependencies are injected through the constructor */ constructor({ httpAgent, deviceMgrUrl, deviceMgrTimeout, deviceModel, tokenGen, errorTemplate, logger, }) { Object.defineProperty(this, 'httpAgent', { value: httpAgent }); Object.defineProperty(this, 'deviceMgrUrl', { value: deviceMgrUrl }); Object.defineProperty(this, 'deviceMgrTimeout', { value: deviceMgrTimeout }); Object.defineProperty(this, 'deviceModel', { value: deviceModel }); Object.defineProperty(this, 'tokenGen', { value: tokenGen }); Object.defineProperty(this, 'error', { value: errorTemplate }); Object.defineProperty(this, 'logger', { value: logger }); } /** * Checks that the device exists for the tenant (if the device belongs to the tenant). * * @param {string} tenant * @param {string} deviceId * * @return {boolean} True if the device exists and belongs to the tenant, otherwise, false. */ async checkDeviceExists(tenant, deviceId) { const cacheHit = await this.deviceModel.contains(tenant, deviceId); if (cacheHit) { return true; } // cache miss... let device = null; try { // recover device from original storage location (DeviceManager microservice) device = await this.getDevice(tenant, deviceId); } catch (ex) { throw this.error.BadGateway('Could not connect to the Device Manager service to validate the device identifier.'); } if (device) { await this.deviceModel.insert(tenant, device.id); return true; } // device does not exist or does not belong to the tenant. return false; } /** * Gets the device from the original storage location. * * @param {string} tenant * @param {string} deviceId */ async getDevice(tenant, deviceId) { const token = await this.tokenGen.generate({ tenant }); const options = { protocol: this.deviceMgrUrl.protocol, host: this.deviceMgrUrl.hostname, port: this.deviceMgrUrl.port, path: `${this.deviceMgrUrl.pathname}/${encodeURIComponent(deviceId)}`, headers: { Authorization: `Bearer ${token}` }, timeout: this.deviceMgrTimeout, }; // call DeviceManager microservice... return this.callDeviceManager(options); } async callDeviceManager(options) { return new Promise((resolve, reject) => { const request = this.httpAgent.get(options, (response) => { let rawData = ''; response.on('data', (chunk) => { rawData += chunk; }); response.on('end', () => { try { if (response.statusCode === 200) { const data = JSON.parse(rawData); resolve(data); } else { // Device not found, resolve with null resolve(null); } } catch (ex) { this.logger.error('Call DeviceManager microservice - Data error', ex); reject(ex); } }); }); request.on('timeout', () => { // Emitted when the underlying socket times out from inactivity. // This only notifies that the socket has been idle, the request // must be aborted manually... // Deprecated since: v14.1.0, v13.14.0 request.abort(); // when we evolve the version of Node.js to 14.x LTS, // we should use .destroy() instead of .abort(): // request.destroy(new Error('Call DeviceManager microservice - Connection timeout')); reject(new Error('Call DeviceManager microservice - Connection timeout')); }); request.on('error', (ex) => { this.logger.error('Call DeviceManager microservice - Connection error', ex); reject(ex); }); }); } }
JavaScript
class GatewayProfile { /** * Create a GatewayProfile. * @member {string} [dataPlaneServiceBaseAddress] The Dataplane connection * URL. * @member {string} [gatewayId] The ID of the gateway. * @member {string} [environment] The environment for the gateway (DEV, * DogFood, or Production). * @member {string} [upgradeManifestUrl] Gateway upgrade manifest URL. * @member {string} [messagingNamespace] Messaging namespace. * @member {string} [messagingAccount] Messaging Account. * @member {string} [messagingKey] Messaging Key. * @member {string} [requestQueue] Request queue name. * @member {string} [responseTopic] Response topic name. * @member {string} [statusBlobSignature] The gateway status blob SAS URL. */ constructor() { } /** * Defines the metadata of GatewayProfile * * @returns {object} metadata of GatewayProfile * */ mapper() { return { required: false, serializedName: 'GatewayProfile', type: { name: 'Composite', className: 'GatewayProfile', modelProperties: { dataPlaneServiceBaseAddress: { required: false, serializedName: 'dataPlaneServiceBaseAddress', type: { name: 'String' } }, gatewayId: { required: false, serializedName: 'gatewayId', type: { name: 'String' } }, environment: { required: false, serializedName: 'environment', type: { name: 'String' } }, upgradeManifestUrl: { required: false, serializedName: 'upgradeManifestUrl', type: { name: 'String' } }, messagingNamespace: { required: false, serializedName: 'messagingNamespace', type: { name: 'String' } }, messagingAccount: { required: false, serializedName: 'messagingAccount', type: { name: 'String' } }, messagingKey: { required: false, serializedName: 'messagingKey', type: { name: 'String' } }, requestQueue: { required: false, serializedName: 'requestQueue', type: { name: 'String' } }, responseTopic: { required: false, serializedName: 'responseTopic', type: { name: 'String' } }, statusBlobSignature: { required: false, serializedName: 'statusBlobSignature', type: { name: 'String' } } } } }; } }
JavaScript
class BlogPostItem extends React.Component { static propTypes = { excerpt: PropTypes.string, fields: PropTypes.shape({ slug: PropTypes.string, tags: PropTypes.array, }), frontmatter: PropTypes.shape({ author: PropTypes.string, date: PropTypes.string, image: PropTypes.any, subTitle: PropTypes.string, title: PropTypes.string, }), timeToRead: PropTypes.number, }; static defaultProps = { frontmatter: { subTitle: null, }, }; state = {hovered: false}; _renderSubtitle = subTitle => ( <h4 className="mt0 mb3 sans-serif mr4 f6 gray">{subTitle}</h4> ); render() { const {fields, frontmatter, timeToRead} = this.props; const {hovered} = this.state; const imageWrapperStyle = { transform: `scale(${hovered ? '1.02' : '1'})`, opacity: `${hovered ? 1 : 0.8}`, transition: 'all 250ms ease-out', }; return ( <GatsbyLink className="BlogPostItem bg-near-white flex pa3 mv4 br2 pointer no-underline translate-y-2" onMouseEnter={() => this.setState({hovered: true})} onMouseLeave={() => this.setState({hovered: false})} to={fields.slug} > <div className="flex flex-column w-70 justify-between"> <h3 className="mt3 mb0 near-black sans-serif mr4"> {frontmatter.title} </h3> {frontmatter.subTitle && this._renderSubtitle(frontmatter.subTitle)} <div className="sans-serif near-black"> <div className="flex items-center mv1 f4"> <Gravatar author={frontmatter.author} className="mr1 mt1" size={20} /> <span>{frontmatter.author}</span> </div> <p className="mt1 mb0"> {frontmatter.date} · {timeToRead} min read </p> </div> </div> <div className="w-30 flex flex-column justify-center" style={imageWrapperStyle} > <GatsbyImage sizes={frontmatter.image.childImageSharp.sizes} /> </div> </GatsbyLink> ); } }
JavaScript
class ActionDisplayEntitiesContextOn { /** * Constructs a new <code>ActionDisplayEntitiesContextOn</code>. * @alias module:model/ActionDisplayEntitiesContextOn */ constructor() { ActionDisplayEntitiesContextOn.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>ActionDisplayEntitiesContextOn</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/ActionDisplayEntitiesContextOn} obj Optional instance to populate. * @return {module:model/ActionDisplayEntitiesContextOn} The populated <code>ActionDisplayEntitiesContextOn</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new ActionDisplayEntitiesContextOn(); if (data.hasOwnProperty('type')) { obj['type'] = ApiClient.convertToType(data['type'], 'String'); } if (data.hasOwnProperty('translationKey')) { obj['translationKey'] = ApiClient.convertToType(data['translationKey'], 'String'); } if (data.hasOwnProperty('hideIfContext')) { obj['hideIfContext'] = ApiClient.convertToType(data['hideIfContext'], 'Boolean'); } if (data.hasOwnProperty('idContext')) { obj['idContext'] = ApiClient.convertToType(data['idContext'], 'String'); } } return obj; } }
JavaScript
class Glyph { constructor(data, config, view) { /* not passing constructor allows us to call Glyphs to access functions without the time cost of initial draw, used for measures */ if (data) this.group = this.formatGlyph(data, config, view); } // getters and setters get children() { return this.group.children; } get bounds() { return this.group.getStrokeBounds(); } formatGlyph(data, config, view) { data.name = data.attribute.hasOwnProperty('name') ? data.attribute.name : ''; let fGroup = new paperFull.Group(); fGroup.name = data.name; let labelGroup = new paperFull.Group(); labelGroup.name = data.name + '-label'; fGroup.addChild(labelGroup); let r = this.drawFeature(data, config, view); fGroup.addChild(r); r.info = data.attribute; let fillColor = config.color; if (data.attribute.hasOwnProperty('class')) { if (view.colorClasses.hasOwnProperty(data.attribute.class)) fillColor = view.colorClasses[data.attribute.class]; } let transparent = config.transparent; let t_per = 1 - config.transparent_percent; /** set glyphs stroke */ //TODO: play more with border glyph if (config.hasOwnProperty('border') && config.border || config.hasOwnProperty('stroke_width')) { r.strokeWidth = config.hasOwnProperty('border_width') ? config.border_width : config.hasOwnProperty('stroke_width') ? config.stroke_width : 2; let strokeColor = config.hasOwnProperty('border_color') ? config.border_color : r.info.hasOwnProperty('border_color') ? r.info.border_color : fillColor; r.strokeColor = formatColor(strokeColor); if (transparent) r.strokeColor.alpha = t_per; } else { r.strokeWidth = 0; } /** fill the figure, if it is an option for the glyph */ let fill = config.hasOwnProperty('fill') ? config.fill : 1; if (fill) r.fillColor = formatColor(fillColor); if (transparent) r.fillColor.alpha = t_per; /** draw label */ //TODO: Draw labels // TODO: Figure out if labels offset from item or from group? if (config.draw_label) { let name = data.name || data.attribute.id; let labelOffset = config['label_offset']; let labelY = r.position.y; //position = middle of target let label = new paperFull.PointText({ point: [r.bounds.right, labelY], content: name, strokeSize: 1, fontSize: `${config['font_size']}pt`, fontFamily: config['font_face'], fontWeight: 'normal', fillColor: formatColor(config['label_color']) }); labelGroup.addChild(label); if (offsetSign(labelOffset)) { label.translate(labelOffset, 0); } else { label.translate(r.getStrokeBounds().left - label.getStrokeBounds().right + labelOffset, 0); } } /** pileup */ if (view.pileup) { let xOffset = config.offset; let pGap = xOffset >= +0 ? config.pileup_gap : -config.pileup_gap; fGroup.translate(new paperFull.Point(collisionOffset(fGroup, view, xOffset, config.offsetDir, pGap), 0)); } /** Attach Popover Listener */ r.onClick = e => { e.preventDefault(); let pt = fGroup.localToGlobal(fGroup.getStrokeBounds().rightCenter).add(new paperFull.Point(paperFull.view.element.offsetLeft, paperFull.view.element.offsetTop)); let cl = paperFull.projects[0].layers['cvitLayer'].children[0]; if (cl.children['cvitPtr']) cl.children['cvitPtr'].remove(); let ptrGrp = new paperFull.Group(); ptrGrp.name = 'cvitPtr'; ptrGrp.strokeWidth = 2; ptrGrp.strokeColor = 'white'; let innerCross = new paperFull.CompoundPath({ children: [new paperFull.Path.Line(e.point.add({ x: 0, y: 1 }), e.point.add({ x: 0, y: 3 })), new paperFull.Path.Line(e.point.add({ x: 0, y: -1 }), e.point.add({ x: 0, y: -3 })), new paperFull.Path.Line(e.point.add({ y: 0, x: 1 }), e.point.add({ y: 0, x: 3 })), new paperFull.Path.Line(e.point.add({ y: 0, x: -1 }), e.point.add({ y: 0, x: -3 }))], strokeColor: 'white', strokeWidth: 2 }); ptrGrp.addChild(innerCross); let outerCross = new paperFull.CompoundPath({ children: [new paperFull.Path.Line(e.point.add({ x: 0, y: 3 }), e.point.add({ x: 0, y: 6 })), new paperFull.Path.Line(e.point.add({ x: 0, y: -3 }), e.point.add({ x: 0, y: -6 })), new paperFull.Path.Line(e.point.add({ y: 0, x: 3 }), e.point.add({ y: 0, x: 6 })), new paperFull.Path.Line(e.point.add({ y: 0, x: -3 }), e.point.add({ y: 0, x: -6 }))], strokeColor: 'black', strokeWidth: 2 }); ptrGrp.addChild(outerCross); cl.addChild(ptrGrp); view.setPopover({ visible: true, position: { x: pt.x, y: pt.y }, data: [data] }); e.stopPropagation(); }; return fGroup; } /** * This needs to be extended by the actual glyph but * formats the actual drawn glyph * * @param data * @param config * @param view * @returns object */ drawFeature(data, config, view) { if (data && config && view) { let topLeft = new paperFull.Point(0, 0); let rectSize = new paperFull.Size(1, 1); return new paperFull.Path.Rectangle(new paperFull.Rectangle(topLeft, rectSize)); } } }
JavaScript
class Border extends Glyph { drawFeature(data, config, view) { let featureWidth = view.chrBounds.width; let featureHeight = (data.end - data.start) * view.yScale; let yLoc = (data.start - view.min) * view.yScale + view.yOffset.offsetTop + view.yAdjust; let xLoc = view.chrBounds.left; let point = new paperFull.Point(xLoc, yLoc); let size = new paperFull.Size(featureWidth, featureHeight); return new paperFull.Path.Rectangle(new paperFull.Rectangle(point, size)); } }
JavaScript
class Centromere extends Glyph { drawFeature(data, config, view) { let overhang = parseInt(config.centromere_overhang); let featureWidth = 2 * overhang + view.chrBounds.width; let featureHeight = (data.end - data.start) * view.yScale; if (featureHeight < 2) featureHeight = 2; let yLoc = (data.start - view.min) * view.yScale + view.yOffset.offsetTop + view.yAdjust; let xLoc = view.chrBounds.left - overhang; let point = new paperFull.Point(xLoc, yLoc); let size = new paperFull.Size(featureWidth, featureHeight); return new paperFull.Path.Rectangle(new paperFull.Rectangle(point, size)); } }
JavaScript
class Chromosome { constructor(data, config, view) { this.positionTree = rbush_1(); this.seqName = data.seqName; this.group = this.formatChromosome(data, config, view); } // getters and setters get children() { return this.group.children; } get labelGroup() { return this.group.children[`${this.seqName}-label`]; } formatChromosome(data, config, view) { let group = new paperFull.Group(); group.name = this.seqName; let labelGroup = new paperFull.Group(); labelGroup.name = this.seqName + '-label'; group.addChild(labelGroup); let xPos = view.xOffset; let yPos = view.yOffset.offsetTop + view.yAdjust; let startOffset = (data.start - view.min) * view.yScale; let point = new paperFull.Point(xPos, yPos + startOffset); let size = new paperFull.Size(view.chrWidth, (data.end - data.start) * view.yScale); let rectangle = new paperFull.Rectangle(point, size); let r = new paperFull.Path.Rectangle(rectangle); r.info = data.attribute; r.thisColor = 'black'; r.fillColor = formatColor(config.chrom_color); if (config.chrom_border === 1) { r.strokeWidth = config.chrom_border_width ? config.chrom_border_width : 2; r.strokeColor = formatColor(config.chrom_border_color); } r.name = group.name; group.addChild(r); point.x = xPos + view.chrWidth / 2; point.y = yPos - view.chrWidth; let label = new paperFull.PointText(point); label.justification = 'center'; label.fontFamily = config.chrom_font_face; label.content = data.attribute.hasOwnProperty('name') ? data.attribute.name : group.name; label.fontSize = config.chrom_font_size; label.fillColor = formatColor(config.chrom_label_color); label.name = group.name + 'Label'; labelGroup.addChild(label); return group; } /** * simple console log to make sure class is loading properly */ static test() { console.log('Access of centromere glyph'); } }
JavaScript
class Marker extends Glyph { drawFeature(data, config, view) { let featureWidth = config.width; let yLoc = (data.start - view.min) * view.yScale + view.yOffset.offsetTop + view.yAdjust; let xOffset = config.offset; let chrEdge = config.offsetDir ? view.chrBounds.right : view.chrBounds.left - featureWidth; let xLoc = chrEdge + xOffset; let point = new paperFull.Point(xLoc, yLoc); return new paperFull.Path.Line(point, new paperFull.Point(point.x + featureWidth, point.y)); } }
JavaScript
class Range extends Glyph { drawFeature(data, config, view) { let featureWidth = config.width; let yLoc = (data.start - view.min) * view.yScale + view.yOffset.offsetTop + view.yAdjust; let xOffset = config.offset; let chrEdge = config.offsetDir ? view.chrBounds.right : view.chrBounds.left - featureWidth; let xLoc = chrEdge + xOffset; let point = new paperFull.Point(xLoc, yLoc); let size = new paperFull.Size(featureWidth, (data.end - data.start) * view.yScale); return new paperFull.Path.Rectangle(new paperFull.Rectangle(point, size)); } }
JavaScript
class Rect extends Glyph { drawFeature(data, config, view) { let featureWidth = config.width; let yLoc = (data.start - view.min) * view.yScale + view.yOffset.offsetTop + view.yAdjust; let xOffset = config.offset; let chrEdge = config.offsetDir ? view.chrBounds.right : view.chrBounds.left - featureWidth; let xLoc = chrEdge + xOffset; let point = new paperFull.Point(xLoc, yLoc); let size = new paperFull.Size(featureWidth, featureWidth); return new paperFull.Path.Rectangle(new paperFull.Rectangle(point, size)); } }
JavaScript
class Doublecircle extends Glyph { drawFeature(data, config, view) { let featureWidth = config.width; let radius = featureWidth / 2; let xOffset = config.offset; let chrEdge = config.offsetDir ? view.chrBounds.right : view.chrBounds.left - featureWidth; let yLoc = (data.start - view.min) * view.yScale + view.yOffset.offsetTop + view.yAdjust; let xLoc = chrEdge + xOffset; // let point = new paper.Point(xLoc, yLoc); return new paperFull.CompoundPath({ children: [new paperFull.Path.Circle({ center: new paperFull.Point(xLoc + radius / 2, yLoc + radius / 2), radius: radius / 2 }), new paperFull.Path.Circle({ center: new paperFull.Point(xLoc + (radius + radius / 2), yLoc + radius / 2), radius: radius / 2 })] }); } }
JavaScript
class Circle extends Glyph { drawFeature(data, config, view) { let featureWidth = config.width; let radius = featureWidth / 2; let xOffset = config.offset; let chrEdge = config.offsetDir ? view.chrBounds.right : view.chrBounds.left - featureWidth; let yLoc = (data.start - view.min) * view.yScale + view.yOffset.offsetTop + view.yAdjust; let xLoc = chrEdge + xOffset; let point = new paperFull.Point(xLoc, yLoc); return new paperFull.Path.Circle(point.add(radius), radius); } }
JavaScript
class Histogram extends Range { constructor(data, config, view) { super(data, config, view); let range = this.group.children[1]; let mc = view.measureConfig; let max = mc.max; let min = mc.min; let val = config.value_type === 'value_attr' ? data.attribute.value : data.score; if (config.value_distribution !== 'linear') val = transformValue(val, config.value_distribution, config.value_base); if (val < min) val = min; if (val > max) val = max; let offset = calculateDistance(val, { start: config.offset, stop: config.offset + config.max_distance }, { start: min, stop: max }, config.invert_value); if (!config.offsetDir) { offset = -offset; range.translate(config.width, 0); } range.bounds.width = offset; /** if labelOffset and offset are same direction, shift label) */ if (offsetSign(config.label_offset) === config.offsetDir) { this.group.children[0].translate(offset, 0); } } }
JavaScript
class Heat extends Glyph { constructor(data, config, view) { super(); this.drawFeature = getDrawFeature(config.draw_as, config.shape); let mc = view.measureConfig; if (config.bin_max !== 0 && mc.max !== config.maxScore) mc.max = config.bin_max; if (config.bin_min !== 0 && mc.min !== config.minScore) mc.min = config.bin_min; let max = mc.max; let min = mc.min; let val = config.value_type === 'value_attr' ? data.attribute.value : data.score; if (config.value_distribution !== 'linear') val = transformValue(val, config.value_distribution, config.value_base); let fc; let colorArray = config.heat_colors; let invert = config.invert_value; if (colorArray === 'redgreen') colorArray = ['#FF0000', '#00FF00']; if (colorArray === 'greyscale') colorArray = ['#000000', '#ffffff']; if (val <= min) { fc = invert ? formatColor(colorArray[colorArray.length - 1]) : formatColor(colorArray[0]); } else if (val >= max) { fc = invert ? formatColor(colorArray[0]) : formatColor(colorArray[colorArray.length - 1]); } else { fc = calculateColor(colorArray, min, max, val, invert); } if (config.transparent) fc.alpha = 1 - config.transparent_percent; this.group = this.formatGlyph(data, config, view); config.draw_as === 'marker' ? this.group.children[1].strokeColor = fc : this.group.children[1].fillColor = fc; } }
JavaScript
class Distance extends Glyph { constructor(data, config, view) { super(); this.drawFeature = getDrawFeature(config.draw_as, config.shape); let mc = view.measureConfig; this.group = this.formatGlyph(data, config, view); let max = mc.max; let min = mc.min; let val = config.value_type === 'value_attr' ? data.attribute.value : data.score; if (config.value_distribution !== 'linear') val = transformValue(val, config.value_distribution, config.value_base); if (val < min) val = min; if (val > max) val = max; let offset = calculateDistance(val, { start: config.offset, stop: config.offset + config.max_distance }, { start: min, stop: max }, config.invert_value); this.group.translate(config.offsetDir ? offset : -offset, 0); } }
JavaScript
class StackedBar extends Glyph { constructor(data, config, view) { super(); this.drawFeature = getDrawFeature('range'); let mc = view.measureConfig; let lastOffset = 0; this.group = this.formatGlyph(data, config, view); this.group.children[1].remove(); for (let key in view.colorClasses) { if (view.colorClasses.hasOwnProperty(key) && (data.attribute.hasOwnProperty(key) || data.attribute.hasOwnProperty(key.toLowerCase()))) { let val = data.attribute[key] || data.attribute[key.toLowerCase()]; let offset = calculateDistance(val, { start: config.offset, stop: config.offset + config.max_distance }, { start: mc.min, stop: mc.max }); offset = config.offsetDir ? offset : -offset; config.color = view.colorClasses[key]; let bar = this.formatGlyph(data, config, view); bar.bounds.width = offset; bar.translate(lastOffset, 0); this.group.insertChild(1, bar); lastOffset += offset; } } /** shift label if the stack grows in direction of label */ if (config.draw_label && offsetSign(config.label_offset) === config.offsetDir) { this.group.children[0].translate(lastOffset, 0); } } }
JavaScript
class Ratio extends StackedBar { constructor(data, config, view) { view.measureConfig.max = data.attribute.value; super(data, config, view); } }
JavaScript
class RectTool extends Component { constructor() { super(); this.onClick = this.onClick.bind(this); this.state = { tool: null }; } drawRect(start, end) { let box = new paperFull.Path.Rectangle(start, end); box.strokeWidth = 2; box.strokeColor = this.props.colors.color1; box.dashArray = [2, 2]; box.isErasable = true; box.fillColor = this.props.colors.color2; paperFull.view.draw(); return box; } componentDidMount() { let tool = new paperFull.Tool(); tool.name = 'rect'; tool.omd = e => { // mouse down document.body.style.cursor = 'crosshair'; // if (!paper.project.color1) { // paper.project.color1 = new paper.Color(0, 0, 0, 1); // } // if (!paper.project.color2) { // paper.project.color2 = new paper.Color(0.7, 0.8, 0.8, 0.4); // } let pt = new paperFull.Point(e.layerX, e.layerY); tool.box = this.drawRect(pt, pt); tool.dwnPt = pt; }; tool.omm = e => { // mouse move this.state.tool.box.remove(); let pt = new paperFull.Point(e.layerX, e.layerY); tool.box = this.drawRect(tool.dwnPt, pt); }; tool.omu = e => { //mouse up this.state.tool.box.remove(); let pt = new paperFull.Point(e.layerX, e.layerY); tool.box = this.drawRect(tool.dwnPt, pt); document.body.style.cursor = 'default'; }; this.setState({ tool: tool }); } componentWillUnmount() { this.state.tool.remove(); } onClick(e) { e.preventDefault(); this.props.selectTool('rect'); this.state.tool.activate(); } render(props, state) { return h("span", { title: 'Draw Rectangle' }, h("button", { className: 'u-full-width cvit-button', onClick: this.onClick, disabled: props.active === 'rect' }, h("i", { className: 'material-icons' }, " ", 'crop_square', " "))); } }
JavaScript
class ColorSelector extends Component { constructor(props) { super(props); this.onClick = this.onClick.bind(this); } onClick(e) { e.preventDefault(); this.props.changeModal(this.props.target); } render(props, state) { return h("span", { title: props.target === 'color1' ? 'Select Line Color' : 'Select Fill Color' }, h("button", { className: 'u-full-width cvit-button', onClick: this.onClick }, h("i", { className: 'material-icons', style: { color: props.color.toCSS() } }, 'stop'))); } }
JavaScript
class QueryString { constructor() { this._data = [lib.parse(location.search, { ignoreQueryPrefix: true, encode: false, strictNullHandling: true })] || [{}]; } get data() { return this._data[0]; } get tag() { return this._data[0].data || 'general'; } get config() { return this._data[0].config || null; } get gff() { let gff = this._data[0].gff || null; if (typeof gff === 'string') gff = [gff]; return gff; } }
JavaScript
class MyStorage{ constructor(key){ this.key = key; } set(object){ localStorage.setItem(this.key, JSON.stringify(object)); } get(){ return JSON.parse(localStorage.getItem(this.key)); } clear(){ localStorage.removeItem(this.key); } }
JavaScript
class Symbol { constructor(x, y, speed, first, opacity) { this._x = x; this._y = y; this._speed = speed; this._first = first; this._opacity = opacity; this._switchInterval = round(random(2, 25)); this._value = null; } // getter and setter get first() { return this._first; } get x() { return this._x; } get y() { return this._y; } get opacity() { return this._opacity; } get value() { return this._value; } /** * Sets a random character from one of the Katakana characters * Called from within the stream class */ setToRandomSymbol() { let charType = round(random(0, 5)); if (frameCount % this._switchInterval === 0) { if (charType > 1) { // set it to Katakana this._value = String.fromCharCode( 0x30A0 + round(random(0, 96)) ); } else { // set it to numeric this._value = round(random(0,9)); } } } /** * Changes the y-position on every frame, based on the 'speed' value * Called from within the stream class */ rain() { this._y = (this._y >= height) ? 0 : this._y += this._speed; } }
JavaScript
class LockHashUtils { /** * Perform SHA3_256 hash * @param input buffer to be hashed * @returns {string} Hash in hexidecimal format */ static Op_Sha3_256(input) { return js_sha3_1.sha3_256.create().update(input).hex().toUpperCase(); } /** * Perform SHA256 hash * @param input buffer to be hashed * @returns {string} Hash in hexidecimal format */ static Op_Hash_256(input) { const hash = js_sha256_1.sha256(input); return js_sha256_1.sha256(Buffer.from(hash, 'hex')).toUpperCase(); } /** * Perform ripemd160 hash * @param input buffer to be hashed * @returns {string} Hash in hexidecimal format */ static Op_Hash_160(input) { const sha256Hash = js_sha256_1.sha256(input); return new ripemd160().update(Buffer.from(sha256Hash, 'hex')).digest('hex').toUpperCase(); } /** * Perform hash for SecretLock with proficed hash algorithm * @param hashAlgorithm Hash algorithm * @param input buffer to be hashed * @returns {string} Hash in hexidecimal format */ static Hash(hashAlgorithm, input) { switch (hashAlgorithm) { case LockHashAlgorithm_1.LockHashAlgorithm.Op_Hash_160: return LockHashUtils.Op_Hash_160(input); case LockHashAlgorithm_1.LockHashAlgorithm.Op_Hash_256: return LockHashUtils.Op_Hash_256(input); case LockHashAlgorithm_1.LockHashAlgorithm.Op_Sha3_256: return LockHashUtils.Op_Sha3_256(input); default: throw new Error('HashAlgorithm is invalid.'); } } }
JavaScript
class SegmentLoader extends videojs.EventTarget { constructor(options) { super(); // check pre-conditions if (!options) { throw new TypeError('Initialization options are required'); } if (typeof options.currentTime !== 'function') { throw new TypeError('No currentTime getter specified'); } if (!options.mediaSource) { throw new TypeError('No MediaSource specified'); } let settings = videojs.mergeOptions(videojs.options.hls, options); // public properties this.state = 'INIT'; this.bandwidth = settings.bandwidth; this.throughput = {rate: 0, count: 0}; this.roundTrip = NaN; this.resetStats_(); this.mediaIndex = null; // private settings this.hasPlayed_ = settings.hasPlayed; this.currentTime_ = settings.currentTime; this.seekable_ = settings.seekable; this.seeking_ = settings.seeking; this.setCurrentTime_ = settings.setCurrentTime; this.mediaSource_ = settings.mediaSource; this.hls_ = settings.hls; this.loaderType_ = settings.loaderType; // private instance variables this.checkBufferTimeout_ = null; this.error_ = void 0; this.currentTimeline_ = -1; this.xhr_ = null; this.pendingSegment_ = null; this.mimeType_ = null; this.sourceUpdater_ = null; this.xhrOptions_ = null; // Fragmented mp4 playback this.activeInitSegmentId_ = null; this.initSegments_ = {}; this.decrypter_ = settings.decrypter; // Manages the tracking and generation of sync-points, mappings // between a time in the display time and a segment index within // a playlist this.syncController_ = settings.syncController; this.syncPoint_ = { segmentIndex: 0, time: 0 }; this.syncController_.on('syncinfoupdate', () => this.trigger('syncinfoupdate')); // ...for determining the fetch location this.fetchAtBuffer_ = false; if (settings.debug) { this.logger_ = videojs.log.bind(videojs, 'segment-loader', this.loaderType_, '->'); } } /** * reset all of our media stats * * @private */ resetStats_() { this.mediaBytesTransferred = 0; this.mediaRequests = 0; this.mediaTransferDuration = 0; this.mediaSecondsLoaded = 0; } /** * dispose of the SegmentLoader and reset to the default state */ dispose() { this.state = 'DISPOSED'; this.abort_(); if (this.sourceUpdater_) { this.sourceUpdater_.dispose(); } this.resetStats_(); } /** * abort anything that is currently doing on with the SegmentLoader * and reset to a default state */ abort() { if (this.state !== 'WAITING') { if (this.pendingSegment_) { this.pendingSegment_ = null; } return; } this.abort_(); // don't wait for buffer check timeouts to begin fetching the // next segment if (!this.paused()) { this.state = 'READY'; this.monitorBuffer_(); } } /** * abort all pending xhr requests and null any pending segements * * @private */ abort_() { if (this.xhr_) { this.xhr_.abort(); } // clear out the segment being processed this.pendingSegment_ = null; } /** * set an error on the segment loader and null out any pending segements * * @param {Error} error the error to set on the SegmentLoader * @return {Error} the error that was set or that is currently set */ error(error) { if (typeof error !== 'undefined') { this.error_ = error; } this.pendingSegment_ = null; return this.error_; } /** * load a playlist and start to fill the buffer */ load() { // un-pause this.monitorBuffer_(); // if we don't have a playlist yet, keep waiting for one to be // specified if (!this.playlist_) { return; } // not sure if this is the best place for this this.syncController_.setDateTimeMapping(this.playlist_); // if all the configuration is ready, initialize and begin loading if (this.state === 'INIT' && this.mimeType_) { return this.init_(); } // if we're in the middle of processing a segment already, don't // kick off an additional segment request if (!this.sourceUpdater_ || (this.state !== 'READY' && this.state !== 'INIT')) { return; } this.state = 'READY'; } /** * Once all the starting parameters have been specified, begin * operation. This method should only be invoked from the INIT * state. * * @private */ init_() { this.state = 'READY'; this.sourceUpdater_ = new SourceUpdater(this.mediaSource_, this.mimeType_); this.resetEverything(); return this.monitorBuffer_(); } /** * set a playlist on the segment loader * * @param {PlaylistLoader} media the playlist to set on the segment loader */ playlist(newPlaylist, options = {}) { if (!newPlaylist) { return; } let oldPlaylist = this.playlist_; let segmentInfo = this.pendingSegment_; this.playlist_ = newPlaylist; this.xhrOptions_ = options; // when we haven't started playing yet, the start of a live playlist // is always our zero-time so force a sync update each time the playlist // is refreshed from the server if (!this.hasPlayed_()) { newPlaylist.syncInfo = { mediaSequence: newPlaylist.mediaSequence, time: 0 }; } // in VOD, this is always a rendition switch (or we updated our syncInfo above) // in LIVE, we always want to update with new playlists (including refreshes) this.trigger('syncinfoupdate'); // if we were unpaused but waiting for a playlist, start // buffering now if (this.mimeType_ && this.state === 'INIT' && !this.paused()) { return this.init_(); } if (!oldPlaylist || oldPlaylist.uri !== newPlaylist.uri) { if (this.mediaIndex !== null) { // we must "resync" the segment loader when we switch renditions and // the segment loader is already synced to the previous rendition this.resyncLoader(); } // the rest of this function depends on `oldPlaylist` being defined return; } // we reloaded the same playlist so we are in a live scenario // and we will likely need to adjust the mediaIndex let mediaSequenceDiff = newPlaylist.mediaSequence - oldPlaylist.mediaSequence; this.logger_('mediaSequenceDiff', mediaSequenceDiff); // update the mediaIndex on the SegmentLoader // this is important because we can abort a request and this value must be // equal to the last appended mediaIndex if (this.mediaIndex !== null) { this.mediaIndex -= mediaSequenceDiff; } // update the mediaIndex on the SegmentInfo object // this is important because we will update this.mediaIndex with this value // in `handleUpdateEnd_` after the segment has been successfully appended if (segmentInfo) { segmentInfo.mediaIndex -= mediaSequenceDiff; // we need to update the referenced segment so that timing information is // saved for the new playlist's segment, however, if the segment fell off the // playlist, we can leave the old reference and just lose the timing info if (segmentInfo.mediaIndex >= 0) { segmentInfo.segment = newPlaylist.segments[segmentInfo.mediaIndex]; } } this.syncController_.saveExpiredSegmentInfo(oldPlaylist, newPlaylist); } /** * Prevent the loader from fetching additional segments. If there * is a segment request outstanding, it will finish processing * before the loader halts. A segment loader can be unpaused by * calling load(). */ pause() { if (this.checkBufferTimeout_) { window.clearTimeout(this.checkBufferTimeout_); this.checkBufferTimeout_ = null; } } /** * Returns whether the segment loader is fetching additional * segments when given the opportunity. This property can be * modified through calls to pause() and load(). */ paused() { return this.checkBufferTimeout_ === null; } /** * create/set the following mimetype on the SourceBuffer through a * SourceUpdater * * @param {String} mimeType the mime type string to use */ mimeType(mimeType) { if (this.mimeType_) { return; } this.mimeType_ = mimeType; // if we were unpaused but waiting for a sourceUpdater, start // buffering now if (this.playlist_ && this.state === 'INIT' && !this.paused()) { this.init_(); } } /** * Delete all the buffered data and reset the SegmentLoader */ resetEverything() { this.resetLoader(); this.remove(0, Infinity); } /** * Force the SegmentLoader to resync and start loading around the currentTime instead * of starting at the end of the buffer * * Useful for fast quality changes */ resetLoader() { this.fetchAtBuffer_ = false; this.resyncLoader(); } /** * Force the SegmentLoader to restart synchronization and make a conservative guess * before returning to the simple walk-forward method */ resyncLoader() { this.mediaIndex = null; this.syncPoint_ = null; } /** * Remove any data in the source buffer between start and end times * @param {Number} start - the start time of the region to remove from the buffer * @param {Number} end - the end time of the region to remove from the buffer */ remove(start, end) { if (this.sourceUpdater_) { this.sourceUpdater_.remove(start, end); } } /** * (re-)schedule monitorBufferTick_ to run as soon as possible * * @private */ monitorBuffer_() { if (this.checkBufferTimeout_) { window.clearTimeout(this.checkBufferTimeout_); } this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), 1); } /** * As long as the SegmentLoader is in the READY state, periodically * invoke fillBuffer_(). * * @private */ monitorBufferTick_() { if (this.state === 'READY') { this.fillBuffer_(); } if (this.checkBufferTimeout_) { window.clearTimeout(this.checkBufferTimeout_); } this.checkBufferTimeout_ = window.setTimeout(this.monitorBufferTick_.bind(this), CHECK_BUFFER_DELAY); } /** * fill the buffer with segements unless the sourceBuffers are * currently updating * * Note: this function should only ever be called by monitorBuffer_ * and never directly * * @private */ fillBuffer_() { if (this.sourceUpdater_.updating()) { return; } if (!this.syncPoint_) { this.syncPoint_ = this.syncController_.getSyncPoint(this.playlist_, this.mediaSource_.duration, this.currentTimeline_, this.currentTime_()); } // see if we need to begin loading immediately let segmentInfo = this.checkBuffer_(this.sourceUpdater_.buffered(), this.playlist_, this.mediaIndex, this.hasPlayed_(), this.currentTime_(), this.syncPoint_); if (!segmentInfo) { return; } let isEndOfStream = detectEndOfStream(this.playlist_, this.mediaSource_, segmentInfo.mediaIndex); if (isEndOfStream) { this.mediaSource_.endOfStream(); return; } if (segmentInfo.mediaIndex === this.playlist_.segments.length - 1 && this.mediaSource_.readyState === 'ended' && !this.seeking_()) { return; } // We will need to change timestampOffset of the sourceBuffer if either of // the following conditions are true: // - The segment.timeline !== this.currentTimeline // (we are crossing a discontinuity somehow) // - The "timestampOffset" for the start of this segment is less than // the currently set timestampOffset if (segmentInfo.timeline !== this.currentTimeline_ || ((segmentInfo.startOfSegment !== null) && segmentInfo.startOfSegment < this.sourceUpdater_.timestampOffset())) { this.syncController_.reset(); segmentInfo.timestampOffset = segmentInfo.startOfSegment; } this.currentTimeline_ = segmentInfo.timeline; this.loadSegment_(segmentInfo); } /** * Determines what segment request should be made, given current playback * state. * * @param {TimeRanges} buffered - the state of the buffer * @param {Object} playlist - the playlist object to fetch segments from * @param {Number} mediaIndex - the previous mediaIndex fetched or null * @param {Boolean} hasPlayed - a flag indicating whether we have played or not * @param {Number} currentTime - the playback position in seconds * @param {Object} syncPoint - a segment info object that describes the * @returns {Object} a segment request object that describes the segment to load */ checkBuffer_(buffered, playlist, mediaIndex, hasPlayed, currentTime, syncPoint) { let lastBufferedEnd = 0; let startOfSegment; if (buffered.length) { lastBufferedEnd = buffered.end(buffered.length - 1); } let bufferedTime = Math.max(0, lastBufferedEnd - currentTime); if (!playlist.segments.length) { return null; } // if there is plenty of content buffered, and the video has // been played before relax for awhile if (bufferedTime >= Config.GOAL_BUFFER_LENGTH) { return null; } // if the video has not yet played once, and we already have // one segment downloaded do nothing if (!hasPlayed && bufferedTime >= 1) { return null; } this.logger_('checkBuffer_', 'mediaIndex:', mediaIndex, 'hasPlayed:', hasPlayed, 'currentTime:', currentTime, 'syncPoint:', syncPoint, 'fetchAtBuffer:', this.fetchAtBuffer_, 'bufferedTime:', bufferedTime); // When the syncPoint is null, there is no way of determining a good // conservative segment index to fetch from // The best thing to do here is to get the kind of sync-point data by // making a request if (syncPoint === null) { mediaIndex = this.getSyncSegmentCandidate_(playlist); this.logger_('getSync', 'mediaIndex:', mediaIndex); return this.generateSegmentInfo_(playlist, mediaIndex, null, true); } // Under normal playback conditions fetching is a simple walk forward if (mediaIndex !== null) { this.logger_('walkForward', 'mediaIndex:', mediaIndex + 1); let segment = playlist.segments[mediaIndex]; if (segment && segment.end) { startOfSegment = segment.end; } else { startOfSegment = lastBufferedEnd; } return this.generateSegmentInfo_(playlist, mediaIndex + 1, startOfSegment, false); } // There is a sync-point but the lack of a mediaIndex indicates that // we need to make a good conservative guess about which segment to // fetch if (this.fetchAtBuffer_) { // Find the segment containing the end of the buffer let mediaSourceInfo = getMediaInfoForTime(playlist, lastBufferedEnd, syncPoint.segmentIndex, syncPoint.time); mediaIndex = mediaSourceInfo.mediaIndex; startOfSegment = mediaSourceInfo.startTime; } else { // Find the segment containing currentTime let mediaSourceInfo = getMediaInfoForTime(playlist, currentTime, syncPoint.segmentIndex, syncPoint.time); mediaIndex = mediaSourceInfo.mediaIndex; startOfSegment = mediaSourceInfo.startTime; } this.logger_('getMediaIndexForTime', 'mediaIndex:', mediaIndex, 'startOfSegment:', startOfSegment); return this.generateSegmentInfo_(playlist, mediaIndex, startOfSegment, false); } /** * The segment loader has no recourse except to fetch a segment in the * current playlist and use the internal timestamps in that segment to * generate a syncPoint. This function returns a good candidate index * for that process. * * @param {Object} playlist - the playlist object to look for a * @returns {Number} An index of a segment from the playlist to load */ getSyncSegmentCandidate_(playlist) { if (this.currentTimeline_ === -1) { return 0; } let segmentIndexArray = playlist.segments .map((s, i) => { return { timeline: s.timeline, segmentIndex: i }; }).filter(s => s.timeline === this.currentTimeline_); if (segmentIndexArray.length) { return segmentIndexArray[Math.min(segmentIndexArray.length - 1, 1)].segmentIndex; } return Math.max(playlist.segments.length - 1, 0); } generateSegmentInfo_(playlist, mediaIndex, startOfSegment, isSyncRequest) { if (mediaIndex < 0 || mediaIndex >= playlist.segments.length) { return null; } let segment = playlist.segments[mediaIndex]; return { // resolve the segment URL relative to the playlist uri: segment.resolvedUri, // the segment's mediaIndex at the time it was requested mediaIndex, // whether or not to update the SegmentLoader's state with this // segment's mediaIndex isSyncRequest, startOfSegment, // the segment's playlist playlist, // unencrypted bytes of the segment bytes: null, // when a key is defined for this segment, the encrypted bytes encryptedBytes: null, // The target timestampOffset for this segment when we append it // to the source buffer timestampOffset: null, // The timeline that the segment is in timeline: segment.timeline, // The expected duration of the segment in seconds duration: segment.duration, // retain the segment in case the playlist updates while doing an async process segment }; } /** * load a specific segment from a request into the buffer * * @private */ loadSegment_(segmentInfo) { let segment; let keyXhr; let initSegmentXhr; let segmentXhr; let removeToTime = 0; removeToTime = this.trimBuffer_(segmentInfo); if (removeToTime > 0) { this.sourceUpdater_.remove(0, removeToTime); } segment = segmentInfo.segment; // optionally, request the decryption key if (segment.key) { let keyRequestOptions = videojs.mergeOptions(this.xhrOptions_, { uri: segment.key.resolvedUri, responseType: 'arraybuffer' }); keyXhr = this.hls_.xhr(keyRequestOptions, this.handleResponse_.bind(this)); } // optionally, request the associated media init segment if (segment.map && !this.initSegments_[initSegmentId(segment.map)]) { let initSegmentOptions = videojs.mergeOptions(this.xhrOptions_, { uri: segment.map.resolvedUri, responseType: 'arraybuffer', headers: segmentXhrHeaders(segment.map) }); initSegmentXhr = this.hls_.xhr(initSegmentOptions, this.handleResponse_.bind(this)); } this.pendingSegment_ = segmentInfo; let segmentRequestOptions = videojs.mergeOptions(this.xhrOptions_, { uri: segmentInfo.uri, responseType: 'arraybuffer', headers: segmentXhrHeaders(segment) }); segmentXhr = this.hls_.xhr(segmentRequestOptions, this.handleResponse_.bind(this)); segmentXhr.addEventListener('progress', (event) => { this.trigger(event); }); this.xhr_ = { keyXhr, initSegmentXhr, segmentXhr, abort() { if (this.segmentXhr) { // Prevent error handler from running. this.segmentXhr.onreadystatechange = null; this.segmentXhr.abort(); this.segmentXhr = null; } if (this.initSegmentXhr) { // Prevent error handler from running. this.initSegmentXhr.onreadystatechange = null; this.initSegmentXhr.abort(); this.initSegmentXhr = null; } if (this.keyXhr) { // Prevent error handler from running. this.keyXhr.onreadystatechange = null; this.keyXhr.abort(); this.keyXhr = null; } } }; this.state = 'WAITING'; } /** * trim the back buffer so we only remove content * on segment boundaries * * @private * * @param {Object} segmentInfo - the current segment * @returns {Number} removeToTime - the end point in time, in seconds * that the the buffer should be trimmed. */ trimBuffer_(segmentInfo) { let seekable = this.seekable_(); let currentTime = this.currentTime_(); let removeToTime; // Chrome has a hard limit of 150mb of // buffer and a very conservative "garbage collector" // We manually clear out the old buffer to ensure // we don't trigger the QuotaExceeded error // on the source buffer during subsequent appends // If we have a seekable range use that as the limit for what can be removed safely // otherwise remove anything older than 1 minute before the current play head if (seekable.length && seekable.start(0) > 0 && seekable.start(0) < currentTime) { return seekable.start(0); } removeToTime = currentTime - 60; return removeToTime; } /** * triggered when a segment response is received * * @private */ handleResponse_(error, request) { let segmentInfo; let segment; let view; // timeout of previously aborted request if (!this.xhr_ || (request !== this.xhr_.segmentXhr && request !== this.xhr_.keyXhr && request !== this.xhr_.initSegmentXhr)) { return; } segmentInfo = this.pendingSegment_; segment = segmentInfo.segment; // if a request times out, reset bandwidth tracking if (request.timedout) { this.abort_(); this.bandwidth = 1; this.roundTrip = NaN; this.state = 'READY'; return this.trigger('progress'); } // trigger an event for other errors if (!request.aborted && error) { // abort will clear xhr_ let keyXhrRequest = this.xhr_.keyXhr; this.abort_(); this.error({ status: request.status, message: request === keyXhrRequest ? 'HLS key request error at URL: ' + segment.key.uri : 'HLS segment request error at URL: ' + segmentInfo.uri, code: 2, xhr: request }); this.state = 'READY'; this.pause(); return this.trigger('error'); } // stop processing if the request was aborted if (!request.response) { this.abort_(); return; } if (request === this.xhr_.segmentXhr) { // the segment request is no longer outstanding this.xhr_.segmentXhr = null; segmentInfo.startOfAppend = Date.now(); // calculate the download bandwidth based on segment request this.roundTrip = request.roundTripTime; this.bandwidth = request.bandwidth; this.mediaBytesTransferred += request.bytesReceived || 0; this.mediaRequests += 1; this.mediaTransferDuration += request.roundTripTime || 0; if (segment.key) { segmentInfo.encryptedBytes = new Uint8Array(request.response); } else { segmentInfo.bytes = new Uint8Array(request.response); } } if (request === this.xhr_.keyXhr) { // the key request is no longer outstanding this.xhr_.keyXhr = null; if (request.response.byteLength !== 16) { this.abort_(); this.error({ status: request.status, message: 'Invalid HLS key at URL: ' + segment.key.uri, code: 2, xhr: request }); this.state = 'READY'; this.pause(); return this.trigger('error'); } view = new DataView(request.response); segment.key.bytes = new Uint32Array([ view.getUint32(0), view.getUint32(4), view.getUint32(8), view.getUint32(12) ]); // if the media sequence is greater than 2^32, the IV will be incorrect // assuming 10s segments, that would be about 1300 years segment.key.iv = segment.key.iv || new Uint32Array([ 0, 0, 0, segmentInfo.mediaIndex + segmentInfo.playlist.mediaSequence ]); } if (request === this.xhr_.initSegmentXhr) { // the init segment request is no longer outstanding this.xhr_.initSegmentXhr = null; segment.map.bytes = new Uint8Array(request.response); this.initSegments_[initSegmentId(segment.map)] = segment.map; } if (!this.xhr_.segmentXhr && !this.xhr_.keyXhr && !this.xhr_.initSegmentXhr) { this.xhr_ = null; this.processResponse_(); } } /** * Decrypt the segment that is being loaded if necessary * * @private */ processResponse_() { if (!this.pendingSegment_) { this.state = 'READY'; return; } this.state = 'DECRYPTING'; let segmentInfo = this.pendingSegment_; let segment = segmentInfo.segment; if (segment.key) { // this is an encrypted segment // incrementally decrypt the segment this.decrypter_.postMessage(createTransferableMessage({ source: this.loaderType_, encrypted: segmentInfo.encryptedBytes, key: segment.key.bytes, iv: segment.key.iv }), [ segmentInfo.encryptedBytes.buffer, segment.key.bytes.buffer ]); } else { this.handleSegment_(); } } /** * Handles response from the decrypter and attaches the decrypted bytes to the pending * segment * * @param {Object} data * Response from decrypter * @method handleDecrypted_ */ handleDecrypted_(data) { const segmentInfo = this.pendingSegment_; const decrypted = data.decrypted; if (segmentInfo) { segmentInfo.bytes = new Uint8Array(decrypted.bytes, decrypted.byteOffset, decrypted.byteLength); } this.handleSegment_(); } /** * append a decrypted segement to the SourceBuffer through a SourceUpdater * * @private */ handleSegment_() { if (!this.pendingSegment_) { this.state = 'READY'; return; } this.state = 'APPENDING'; let segmentInfo = this.pendingSegment_; let segment = segmentInfo.segment; this.syncController_.probeSegmentInfo(segmentInfo); if (segmentInfo.isSyncRequest) { this.pendingSegment_ = null; this.state = 'READY'; return; } if (segmentInfo.timestampOffset !== null && segmentInfo.timestampOffset !== this.sourceUpdater_.timestampOffset()) { this.sourceUpdater_.timestampOffset(segmentInfo.timestampOffset); } // if the media initialization segment is changing, append it // before the content segment if (segment.map) { let initId = initSegmentId(segment.map); if (!this.activeInitSegmentId_ || this.activeInitSegmentId_ !== initId) { let initSegment = this.initSegments_[initId]; this.sourceUpdater_.appendBuffer(initSegment.bytes, () => { this.activeInitSegmentId_ = initId; }); } } segmentInfo.byteLength = segmentInfo.bytes.byteLength; if (typeof segment.start === 'number' && typeof segment.end === 'number') { this.mediaSecondsLoaded += segment.end - segment.start; } else { this.mediaSecondsLoaded += segment.duration; } this.sourceUpdater_.appendBuffer(segmentInfo.bytes, this.handleUpdateEnd_.bind(this)); } /** * callback to run when appendBuffer is finished. detects if we are * in a good state to do things with the data we got, or if we need * to wait for more * * @private */ handleUpdateEnd_() { this.logger_('handleUpdateEnd_', 'segmentInfo:', this.pendingSegment_); if (!this.pendingSegment_) { this.state = 'READY'; if (!this.paused()) { this.monitorBuffer_(); } return; } let segmentInfo = this.pendingSegment_; let segment = segmentInfo.segment; let isWalkingForward = this.mediaIndex !== null; this.pendingSegment_ = null; this.recordThroughput_(segmentInfo); this.state = 'READY'; // If we previously appended a segment that ends more than 3 targetDurations before // the currentTime_ that means that our conservative guess was too conservative. // In that case, reset the loader state so that we try to use any information gained // from the previous request to create a new, more accurate, sync-point. if (segment.end && this.currentTime_() - segment.end > segmentInfo.playlist.targetDuration * 3) { this.resetLoader(); } else { this.mediaIndex = segmentInfo.mediaIndex; this.fetchAtBuffer_ = true; } // Don't do a rendition switch unless the SegmentLoader is already walking forward if (isWalkingForward) { this.trigger('progress'); } // any time an update finishes and the last segment is in the // buffer, end the stream. this ensures the "ended" event will // fire if playback reaches that point. let isEndOfStream = detectEndOfStream(segmentInfo.playlist, this.mediaSource_, this.mediaIndex + 1); if (isEndOfStream) { this.mediaSource_.endOfStream(); } if (!this.paused()) { this.monitorBuffer_(); } } /** * Records the current throughput of the decrypt, transmux, and append * portion of the semgment pipeline. `throughput.rate` is a the cumulative * moving average of the throughput. `throughput.count` is the number of * data points in the average. * * @private * @param {Object} segmentInfo the object returned by loadSegment */ recordThroughput_(segmentInfo) { let rate = this.throughput.rate; // Add one to the time to ensure that we don't accidentally attempt to divide // by zero in the case where the throughput is ridiculously high let segmentProcessingTime = Date.now() - segmentInfo.startOfAppend + 1; // Multiply by 8000 to convert from bytes/millisecond to bits/second let segmentProcessingThroughput = Math.floor((segmentInfo.byteLength / segmentProcessingTime) * 8 * 1000); // This is just a cumulative moving average calculation: // newAvg = oldAvg + (sample - oldAvg) / (sampleCount + 1) this.throughput.rate += (segmentProcessingThroughput - rate) / (++this.throughput.count); } /** * A debugging logger noop that is set to console.log only if debugging * is enabled globally * * @private */ logger_() {} }
JavaScript
class SpeakerStatsButton extends AbstractSpeakerStatsButton { /** * Handles clicking / pressing the button, and opens the appropriate dialog. * * @protected * @returns {void} */ _handleClick() { const { dispatch } = this.props; sendAnalytics(createToolbarEvent('speaker.stats')); dispatch(openDialog(SpeakerStats)); } }
JavaScript
class SpinCompiler { /** * Compiles a spin object to a trigger object. */ static compile(spin) { const checked_spin = new Spin(spin.wager, spin.payout, spin.xp); const trigger_object = { 'target': 'player', 'condition': { 'chips': { '$gte': checked_spin.wager } }, 'action': { '$inc': { 'xp' : checked_spin.xp, 'chips': checked_spin.payout - checked_spin.wager, 'spinAccumulated': 1, 'wagerAccumulated': checked_spin.wager, 'payoutAccumulated': checked_spin.payout } } }; //TODO: trigger_object.__proto__ = Trigger.prototype; return trigger_object; } }
JavaScript
class Literally { /** * @constructor * @param {string} string */ constructor(string) { // Just like stripslashes in PHP this._string = string.replace(/\\(.)/mg, '$1') } /** * @return {string} */ toString() { return this._string } }
JavaScript
class BodyParser { constructor (Config) { /** * Giving preference to types from the user config over the * default config, since user can defined empty arrays as * part of ignoring body parsing, which will be overridden * otherwise by the merge method. */ this.config = Config.merge('bodyParser', defaultConfig, (obj, src, key) => { if (key === 'types' && typeof (src) !== 'undefined') { return src } }) this.files = new FormFields() this.fields = new FormFields() } /** * The JSON types to be used for identifying the JSON request. * The values are defined in `config/bodyParser.js` file * under `json` object. * * @attribute jsonTypes * * @type {Array} */ get jsonTypes () { return this.config.json.types } /** * Form types to be used for identifying the form request. * The values are defined in `config/bodyParser.js` file * under `form` object. * * @attribute formTypes * * @type {Array} */ get formTypes () { return this.config.form.types } /** * Raw types to be used for identifying the raw request. * The values are defined in `config/bodyParser.js` * file under `raw` object. * * @attribute rawTypes * * @type {Array} */ get rawTypes () { return this.config.raw.types } /** * Files types to be used for identifying the multipart types. * The values are defined in `config/bodyParser.js` file * under `files` object. * * @attribute filesTypes * * @type {Array} */ get filesTypes () { return this.config.files.types } /** * Parses the JSON body when `Content-Type` is set to * one of the available `this.jsonTypes`. * * @method _parseJSON * * @param {Object} req * * @return {Object} * * @private */ _parseJSON (req) { return parse.json(req, { limit: this.config.json.limit, strict: this.config.json.strict }) } /** * Parses the form body when `Content-type` is set to * one of the available `this.formTypes`. * * @method _parseForm * * @param {Object} req * * @return {Object} * * @private */ _parseForm (req) { return parse.form(req, { limit: this.config.form.limit }) } /** * Parses the raw body when `Content-type` is set to * one of the available `this.rawTypes`. * * @method _parseRaw * * @param {Object} req * * @return {Object} * * @private */ _parseRaw (req) { return parse.text(req, { limit: this.config.raw.limit }) } /** * Returns a boolean indicating whether request is * of a given type. Also makes sure that user * wants to process the given type. * * @method _isType * * @param {Object} request * @param {Array} types * * @return {Boolean} * * @private */ _isType (request, types) { return types && types.length && request.is(types) } /** * Returns a boolean indicating whether or not * the files should be autoProcessed based * on certain conditions * * @method _shouldBeProcessed * * @param {Object} request * * @return {Boolean} * * @private */ _shouldBeProcessed (request) { const autoProcess = this.config.files.autoProcess if (!autoProcess) { return false } if (autoProcess instanceof Array === true && request.match(autoProcess)) { return true } return !request.match(this.config.files.processManually) } /** * Method called by Adonis middleware stack. It will read * the request body as per the config defined inside * `config/bodyParser.js` file. It will set following * private properties on the request object. * * 1. _body - The request body ( JSON or Url endcoded ) * 2. _files - Uploaded files * 3. _raw - The request raw body. * * @method handle * * @param {Object} options.request * @param {Function} next * * @return {void} */ async handle ({ request }, next) { request._files = {} request.body = {} request._raw = {} /** * Don't bother when request does not have body */ if (!request.hasBody()) { debug('skipping body parsing, since request body is empty') await next() return } /** * Body is multipart/form-data and autoProcess is set to * true, so process all the files and fields inside * it. */ if (this._shouldBeProcessed(request) && this._isType(request, this.filesTypes)) { debug('detected multipart body') request.multipart = new Multipart(request, true) request.multipart.file('*', {}, async (file) => { this.files.add(file.fieldName, file) await file.moveToTmp(this.config.files.tmpFileName) }) request.multipart.field((name, value) => { this.fields.add(name, value) }) await request.multipart.process() request._files = this.files.get() request.body = this.fields.get() await next() return } request.multipart = new Multipart(request) /** * Body is JSON, so parse it and move forward */ if (this._isType(request, this.jsonTypes)) { debug('detected json body') request.body = await this._parseJSON(request.request) await next() return } /** * Body is Url encoded form, so parse it and move forward */ if (this._isType(request, this.formTypes)) { debug('detected form body') request.body = await this._parseForm(request.request) await next() return } /** * Body is raw data, parse it and move forward */ if (this._isType(request, this.rawTypes)) { debug('detected raw body') request._raw = await this._parseRaw(request.request) await next() return } /** * Nothing matched, so please move forward */ await next() } }