Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*!
  2.  
  3.  
  4. =========================================================
  5. * Mentr Website - v1.0.0
  6. =========================================================
  7.  
  8. * Copyright 2019 Mentr Team
  9.  
  10. * Coded by Mentr Team
  11.  
  12. =========================================================
  13.  
  14. * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
  15.  
  16.  
  17. */
  18. import React from "react";
  19. import axios from "axios";
  20. import { Button, Comment, Form, Image, Icon, Card as CardSemanticUI } from 'semantic-ui-react'
  21.  
  22.   // reactstrap components
  23. import { Card, CardHeader ,CardBody ,CardTitle ,Container, Row, Alert } from "reactstrap";
  24. import Header from "components/Headers/Header.jsx";
  25. import moment from 'moment';
  26. import "../../assets/css/divider.scss"
  27.  
  28. import { faCanadianMapleLeaf } from '@fortawesome/free-brands-svg-icons';
  29. import { faCrown } from '@fortawesome/free-solid-svg-icons';
  30. import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
  31.  
  32. import { Filter } from 'bad-words';
  33.  
  34. import { Editor } from 'react-draft-wysiwyg';
  35. import { EditorState, convertToRaw } from 'draft-js';
  36. import draftToHtml from 'draftjs-to-html';
  37. import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';
  38. import '../../assets/css/editor.css';
  39.  
  40.  
  41.  
  42.  
  43. class MentorDetails extends React.Component {
  44.     constructor() {
  45.         super();
  46.         this.state = {
  47.             post: null,
  48.             post_id: '',
  49.             users_info: {},
  50.             current_user: {},
  51.             editorState: EditorState.createEmpty(),
  52.         };
  53.     }
  54.     onEditorStateChange = (editorState) => {
  55.       console.log(editorState)
  56.       this.setState({
  57.         editorState,
  58.       });
  59.     };
  60.  
  61.  
  62.  
  63.     componentWillMount() {
  64.         let paths = this.props.location.pathname.split("/")
  65.         let post_id = paths[paths.length-1]
  66.         this.setState({ post_id })
  67.  
  68.         axios.get(`/api/posts/${post_id}`)
  69.         .then(res => {
  70.           if (res.status === 200) {
  71.             const data = res.data
  72.             this.setState({post: data.post});
  73.             // console.log(data.post)
  74.             let replies = data.post.replies
  75.             for(let i = 0; i < replies.length; i++){
  76.               let reply = replies[i]
  77.               let reply_username = reply.username
  78.               axios.get(`/api/users/?name=${reply_username}`)
  79.                .then(res => {
  80.                  if(res.status === 200) {
  81.                    const user = res.data.users[0]
  82.                    const new_users_info = {
  83.                      ...this.state.users_info,
  84.                      [reply_username]: user
  85.                    }
  86.                    this.setState({users_info: new_users_info});
  87.                  }
  88.                })
  89.             }
  90.  
  91.           }else{
  92.             console.log("Unable to get this post by id")
  93.           }
  94.          
  95.         })
  96.       }
  97.       //THIS IS TEST AREA REPLACE BELOW
  98.       // onSubmit (text) {
  99.       //   return event => {
  100.       //     event.preventDefault();
  101.       //     let new_reply = {
  102.       //       content: text,
  103.       //       username: this.props.name
  104.       //     }
  105.       //     this.setState({reply_content: ''})
  106.       //     fetch(`/api/posts/${this.state.post_id}/replies`,  {
  107.       //       method : 'POST',
  108.       //       body: JSON.stringify({
  109.       //         replies: [new_reply]
  110.       //       }),
  111.       //       headers: {
  112.       //         'Content-Type': 'application/json'
  113.       //       }
  114.       //     })
  115.       //     .then(res => {
  116.       //       if ( res.status === 200) {
  117.       //         axios.get(`/api/posts/${this.state.post_id}`)
  118.       //         .then(res => {
  119.       //           if (res.status === 200) {
  120.       //             const data = res.data
  121.       //             this.setState({ post: data.post });
  122.       //           }
  123.       //           this.changeUserPoints(1)
  124.       //         })
  125.       //         console.log('Success')
  126.       //       } else {
  127.       //         alert("Unable to submit reply. Please try again.")
  128.       //       }
  129.       //     })
  130.       //     .catch(err => {
  131.       //       alert('Wrong Email or Password, please try again later')
  132.      
  133.       //     });
  134.       // }
  135.       // }
  136.        
  137.  
  138.       onSubmit (text) {
  139.        
  140.  
  141.         return event => {
  142.          
  143.        
  144.           event.preventDefault();
  145.           let new_reply = {
  146.             content: text,
  147.             username: this.props.name
  148.           }
  149.           this.setState({reply_content: ''})
  150.           fetch(`/api/posts/${this.state.post_id}/replies`,  {
  151.             method : 'POST',
  152.             body: JSON.stringify({
  153.               replies: [new_reply]
  154.             }),
  155.             headers: {
  156.               'Content-Type': 'application/json'
  157.             }
  158.           })
  159.           .then(res => {
  160.             if ( res.status === 200) {
  161.               axios.get(`/api/posts/${this.state.post_id}`)
  162.               .then(res => {
  163.                 if (res.status === 200) {
  164.                   const data = res.data
  165.                   this.setState({ post: data.post });
  166.                 }
  167.                 this.changeUserPoints(1)
  168.               })
  169.               console.log('Success')
  170.             } else {
  171.               alert("Unable to submit reply. Please try again.")
  172.             }
  173.           })
  174.           .catch(err => {
  175.             alert('Wrong Email or Password, please try again later')
  176.      
  177.           });
  178.       }
  179.       }
  180.  
  181.  
  182.       //THIS IS TEST AREA END
  183.  
  184.       isLoggedIn() {
  185.         return this.props.name !== 'Guest'
  186.       }
  187.  
  188.       removeOnClick(reply_id) {
  189.         axios.delete(`/api/posts/${this.state.post_id}/replies/${reply_id}`)
  190.         .then(res => {
  191.           if (res.status === 200) {
  192.             this.changeUserPoints(-1 , reply_username)
  193.             axios.get(`/api/posts/${this.state.post_id}`)
  194.             .then(res => {
  195.               if (res.status === 200) {
  196.             const data = res.data
  197.             this.setState({post: data.post});
  198.           }else{
  199.             console.log("Unable to get this post by id")
  200.           }
  201.         })
  202.       }else{
  203.         console.log("Unable to Delete this reply")
  204.       }
  205.     })
  206.   }
  207.  
  208.   changeUserPoints(delta) {
  209.     let user_name = this.reply_username
  210.     axios.get(`/api/users?name=${user_name}`)
  211.     .then(res => {
  212.       if(res.status === 200) {
  213.         let users = res.data.users
  214.         this.setState({current_user: users});
  215.       if(users.length > 0) {
  216.         let user_found = users[0]
  217.         let user_id = user_found._id
  218.         let new_points = user_found.points + delta
  219.         axios.patch(`/api/users/${user_id}`, {points: new_points}, {})
  220.         .then(res => {
  221.           if(res.status === 200) {
  222.             console.log(`Succesfully incremenet points of user: ${user_name} by ${delta}`)
  223.       }
  224.     })
  225.   }
  226.   }
  227. })
  228. }
  229.  
  230.   getUser(username) {
  231.     if(this.state.users_info[username]) {
  232.       return this.state.users_info[username]
  233.     }else{
  234.       return {}
  235.     }
  236.   }
  237.  
  238.  
  239.     render() {
  240.       const isLoggedIn = this.isLoggedIn()
  241.         if(this.state.post === null){
  242.             return null;
  243.         }
  244.         // console.log(this.state.post)
  245.         let replies = this.state.post.replies
  246.         const { editorState } = this.state;
  247.         let comments = replies.map((reply) => {
  248.           let isSameUser = (reply.username === this.props.name)
  249.        
  250.  
  251.             return (
  252.              
  253.                 <Comment className='row'>
  254.                  
  255.                 {/* <Comment.Avatar as='a' src={`https://ui-avatars.com/api/?background=0D8ABC&color=fff&bold=true&rounded=true&name=${reply.username}` }/> */}
  256.                 <CardSemanticUI className='col-md-2 col-lg-2' style={{maxHeight: '40vh'}}>
  257.                   <Image src={`https://ui-avatars.com/api/?background=0D8ABC&color=fff&bold=true&name=${reply.username}` } wrapped ui={false} />
  258.                   <CardSemanticUI.Content>
  259.                     <CardSemanticUI.Header>{reply.username}</CardSemanticUI.Header>
  260.                     <CardSemanticUI.Meta>
  261.                       <span className='date'>{ moment.parseZone(reply.timestamp).local().fromNow()}</span>
  262.                     </CardSemanticUI.Meta>
  263.  
  264.                     <CardSemanticUI.Description style={(this.getUser(reply.username).userType === "ADMIN") ? {backgroundColor: "#FF2322", borderRadius: '5px'}: (this.getUser(reply.username).userType === "MOD") ? {backgroundColor: "#DAA520", borderRadius: '5px'}: {backgroundColor: "#4D87C1", borderRadius: '5px'}} >
  265.                       <p className="text-center" style={{ fontWeight: 'bold', color: 'white'}}>{this.getUser(reply.username).userType}</p>
  266.                     </CardSemanticUI.Description>
  267.                    
  268.                    
  269.                   </CardSemanticUI.Content>
  270.                   <CardSemanticUI.Content extra>
  271.                    
  272.                  
  273.                   <FontAwesomeIcon icon={faCanadianMapleLeaf}  />
  274.                    <span style={{paddingLeft: '5%', paddingRight: '30%'}}>
  275.                       {this.getUser(reply.username).points}
  276.                   </span>
  277.  
  278.                   <FontAwesomeIcon icon={faCrown}  />
  279.                  <span style={{paddingLeft: '5%'}}>
  280.                       {this.getUser(reply.username).level}
  281.                     </span>
  282.                   </CardSemanticUI.Content>
  283.                 </CardSemanticUI>
  284.                 <Comment.Content className='col-md-10 col-lg-10' style={{paddingLeft: '10%'}}>
  285.                     <Comment.Text style={{fontSize: '130%'}}>
  286.                       <div dangerouslySetInnerHTML={{__html: reply.content}}></div>
  287.                     </Comment.Text>
  288.                     <Comment.Actions>
  289.                     <Comment.Action>
  290.                       <span style={(isSameUser || !isLoggedIn) ? {display: 'none'}: {}}>
  291.                         <i className="ni ni-like-2"></i>
  292.                         <span style={{paddingRight: '10px'}}><a>Love</a></span>
  293.                       </span>
  294.                  {/* <span style={((!isSameUser || !isLoggedIn) && (!this.state.current_user || !this.state.current_user.userType || this.state.current_user.userType !== 'ADMIN')) ? {display: 'none'} : {}}><a onClick={()=>this.removeOnClick(reply._id)}>Remove </a></span> */}
  295.                  {/* <span style={((!isSameUser || !isLoggedIn) && (!this.state.current_user || !this.state.current_user.userType || this.state.current_user.userType !== 'MOD')) ? {display: 'none'} : {}}><a onClick={()=>this.removeOnClick(reply._id)}>Remove </a></span> */}
  296.              
  297.                     </Comment.Action>
  298.                     </Comment.Actions>
  299.                 </Comment.Content>
  300.                 <b className="hrr anim"></b>
  301.                 </Comment>
  302.             )
  303.           })
  304.  
  305.  
  306.         return (
  307.           <>
  308.             <Header />
  309.             {/* Page content */}
  310.             <Container className="mt--7" fluid>
  311.               <Row>
  312.                   <Card body>
  313.                       <CardHeader className="text-primary" style={{fontSize: '200%'}}>{this.state.post.title}</CardHeader>
  314.                       <div style={{paddingLeft: '1.5%'}}>Created By {this.state.post.username} {moment.parseZone (this.state.post.timestamp).local().fromNow()}</div>
  315.                       <CardBody>
  316.                           <div>
  317.                               <CardTitle style={{fontSize: '130%', mariginRight: '25%', lineHeight: '1.5'}}>{this.state.post.content}
  318. </CardTitle>
  319.                           </div>
  320.                           <Comment.Metadata>
  321.                     <div></div>
  322.                     </Comment.Metadata >
  323.                          <Comment.Group size='large' style={{maxWidth: '80%'}}>
  324.                           <b className="hrr anim"></b>
  325.                            {comments}
  326.                         <Form style={(this.state.post.readOnly || this.state.post.readOnly === true) ? {display: 'none'}: {}} reply onSubmit={this.onSubmit(draftToHtml(convertToRaw(editorState.getCurrentContent())))}>
  327.                           <Editor
  328.                               placeholder="Enter Text to reply to this post"
  329.                               toolbarClassName="toolbarClassName"
  330.                               wrapperClassName="wrapperClassName"
  331.                               editorClassName="editorClassName"
  332.                               onEditorStateChange={this.onEditorStateChange}
  333.                             />
  334.                             {/* <div>
  335.                             {draftToHtml(convertToRaw(editorState.getCurrentContent()))}
  336.                             </div> */}
  337.                             <Alert style={isLoggedIn ? {display: 'none'} : {}} color="dark">
  338.                               You have to login in order to reply to this post
  339.                               </Alert>
  340.                             <Button disabled={!isLoggedIn || this.state.post.readOnly === true}  content='Add Comment'  primary />
  341.                             </Form>
  342.                         </Comment.Group>
  343.                     </CardBody>
  344.                   </Card>
  345.               </Row>
  346.             </Container>
  347.           </>
  348.         );
  349.       }
  350. }
  351.  
  352.  
  353.  
  354. export default MentorDetails;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement