Exemplo n.º 1
0
    def __findAndAddScrap(self, scode, userId, jdata):
        htmlScrapper = HtmlScrapper()
        urls = StrUtils.extractUrls(jdata['content'])
        if len(urls) < 1 :
            return
        scrapIds = []
        for url in urls:
            if self.scrapRepository.getScrapListByUrl(scode, url) != None:
                continue
            title, subtitle, body, img_url = htmlScrapper.scrap(url)
            if title is None:
                continue
            scrapId = StrUtils.getMapleUuid('scrapId:')
            queries = []
            queries.append(self.scrapRepository.qInsertScrap(scode, scrapId, url, title, subtitle))
            queries.append(self.scrapBodyRepository.qInsertScrapBody(scode, scrapId, body))
            self.scrapBodyRepository.multiQueries(scode, queries)

            ### Image Crop and Insert DB 
            ### filePath = millisecond +'-'+ original filename
            filePath, fileSize = ImageTool.download(scode, userId, img_url, appconfig.scrap_path)
            if filePath is not None:
                ImageTool.cropImageByFullPath(scode, userId, filePath, appconfig.crop_path)
                fileName = filePath.split('/')[-1]
                self.scrapRepository.updateScrapFile(scode, scrapId, fileName)
            scrapIds.append(scrapId)
        return scrapIds
Exemplo n.º 2
0
    def __userRegister(self, jdata):
        if StrUtils.isEmail(jdata['email']) == False:
            return self.setError('admin', AllError.InvalidEmailFormat)
        if self.adminUserRepository.getUserByEmail(jdata['email']) is not None:
            return self.setError('admin', AllError.ExistEmail)
        if len(jdata['password']) < 8:
            return self.setError('admin', AllError.ShortPasswordLengthThan8)

        userId = StrUtils.getMapleUuid('adminId:')
        if self.adminUserRepository.insert(
                userId, jdata['email'], StrUtils.getSha256(jdata['password']),
                jdata['role'], jdata['userName']) == False:
            return self.setError('admin', AllError.RegisterFailed)
        return self.setOk('admin', userId)
Exemplo n.º 3
0
    def addApp(self, jdata):
        ret = self.__checkAdminToken(jdata)
        if isinstance(ret, dict) and 'result' in ret:
            return ret
        token = ret
        scode = jdata['scode']
        if StrUtils.isAlphaNumeric(scode) == False:
            return self.setError('admin',
                                 AllError.ScodeAllowedOnlyAlphabet.name())
        if self.adminAppRepository.hasSCode(scode) == True:
            return self.setError('admin', AllError.AlreadyExistScode)

        appId = keygen.createKey('appId:')
        appToken = self.adminToken.createApp(appId, scode)

        ret = self.__createAppDatabase(scode, jdata)
        if ret != None:
            return ret
        MultiDbHelper.instance().createTables(scode)
        #appId, userId, scode, token, title, description, status
        if self.adminAppRepository.insertApp(appId, token['userId'], scode,
                                             appToken, jdata['title'],
                                             jdata['description'],
                                             jdata['status']) == False:
            return self.setError('admin', AllError.failedToCreateApp)
        if 'dbHost' in jdata and 'dbPort' in jdata and 'dbUser' in jdata and 'dbPassword' in jdata:
            self.adminAppRepository.updateExternalDbInfo(
                token['userId'], scode, jdata['dbHost'], jdata['dbPort'],
                jdata['dbUser'], jdata['dbPassword'])
        if 'fcmId' in jdata and 'fcmKey' in jdata:
            self.adminAppRepository.updateAdminPush(token['userId'], scode,
                                                    jdata['fcmId'],
                                                    jdata['fcmKey'])
        return self.setOk('admin', {'appId': appId, 'appToken': appToken})
Exemplo n.º 4
0
    def __addBoard(self, scode, userId, userName, jdata, scrapIds):
        boardId = StrUtils.getMapleUuid('boardId:')

        userRec = self.userRepository.getUser(scode, userId)
        if userRec == None or userRec['leftAt'] != None:
            return self.setError(scode, AllError.InvalidUser)
        if self.boardRepository.insert(scode, boardId, userId, userName, jdata['title'], self._getShortContent(jdata['content']), 
                                       jdata['hasImage'], jdata['hasFile'], jdata['category'], jdata['contentType'] if 'contentType' not in jdata else 'text') == False:
            return self.setError(scode, AllError.FailAddBoard)
        
        self.boardContentRepository.insert(scode, boardId, userId, jdata['content'])
        self.boardCountRepository.insert(scode, boardId)

        queries = []        
        if scrapIds is not None and len(scrapIds) > 0:
            for scrapId in scrapIds:
                queries.append(self.boardScrapRepository.qInsertScrap(scode, boardId, scrapId))
        self.boardScrapRepository.multiQueries(scode, queries)

        if 'fileIds' in jdata and len(jdata['fileIds']) > 0:
            self.uploadFileRepository.updateFilesEnabled(scode, jdata['fileIds'], boardId, True)
            fileRec = self.uploadFileRepository.getFile(scode, jdata['fileIds'][0])
            
            if self.imageTool.cropImageByFilename(scode, userId, appconfig.upload_path, fileRec['fileName'], appconfig.crop_path):
                self.fileRepository.updateCropped(scode, fileRec['fileId'], True)

        return self.setOk(scode, {'boardId': boardId})
Exemplo n.º 5
0
    def __registerUser(self, scode, authType, jdata, enableToken):
        userId = jdata['userId'] if 'userId' in jdata else StrUtils.getMapleUuid('userId:') #for anonymous user

        authQuery = None
        if authType == EUserAuthType.idpw:
            authQuery = self.userAuthRepository.qInsertUserNamePw(scode, userId, jdata['userName'], jdata['password'])
        elif authType == EUserAuthType.email:
            authQuery = self.userAuthRepository.qInsertEmail(scode, userId, jdata['email'])
        elif  authType == EUserAuthType.mobile:
            self.userAuthRepository.qInsertPhoneNo(scode, userId, jdata['mobileNo'])
        if authQuery == None:
            return self.setError(scode, AllError.UnknownAuthType)
        tokenId, token = self.loginToken.create(scode, userId, jdata['uuid'], authType)
        queries = []
        if authQuery is not None:
            queries.append(authQuery)
        if 'userName' not in jdata:
            jdata['userName'] = '******' + str(int(round(time.time() * 1000)))

        queries.append(self.userRepository.qInsert(scode, userId, jdata['userName'], authQuery==None))
        
        queries.append(self.userTokenRepository.qInsertToken(scode, userId, jdata['uuid'], tokenId, token, enableToken))
        if self.userRepository.multiQueries(scode, queries) == False:
            return self.setError(scode, AllError.FailedUserRegister)
        return self.setOk(scode, {'loginToken': token})
Exemplo n.º 6
0
    def anonymousLogin(self, scode, jdata):
        appId, scode = self.appToken.parseApp(jdata['appToken'])

        if self.userRepository.findUserName(scode, jdata['userName']) == True:
            return self.setError(scode, AllError.ExistUserName)

        userId = StrUtils.getMapleUuid('anonymous:')
        jdata['userId'] = userId
        jdata['password'] = jdata['userName'] + '!@#$'

        ret = self.registerIdPw(scode, jdata)
        if ret['result'] == 'error':
            return ret
        
        auth = self.userAuthRepository.getUserByUserName(scode, jdata['userName'])
        if auth == None:
            return self.setError(scode, AllError.FailToCreateAnonymousAccount)
        
        tokenRec = self.userTokenRepository.getTokenByUserId(scode, userId)
        if tokenRec == None:
            return self.setError(scode, AllError.UnauthorizedAnonymousUserId)
        
        self.userPushRepository.insert(scode, userId, tokenRec['uuid'], jdata['epid'] if 'epid' in jdata else '')
        self.userRepository.updateUserDetail(scode, userId, 
                jdata['osType'] if 'osType' in jdata else '', 
                jdata['osVersion'] if 'osVersion' in jdata else '', 
                jdata['appVersion']if 'appVersion' in jdata else '')
        return self.setOk(scode, {'loginToken': tokenRec['token']})
Exemplo n.º 7
0
 def adminLogin(self, jdata):
     user = self.adminUserRepository.getUserByEmail(jdata['email'])
     if user == None:
         return self.setError('admin', AllError.NotExistUser)
     if StrUtils.getSha256(jdata['password']) != user['password']:
         return self.setError('admin', AllError.WrongAccountInfo)
     token = self.adminToken.createUser(user['userId'], user['userRole'],
                                        user['userName'])
     self.adminTokenRepository.upsert(user['userId'], token, '0.0.0.0')
     return self.setOk('admin', {'userId': user['userId'], 'token': token})
Exemplo n.º 8
0
 def registerEmail(self, scode, jdata):
     if StrUtils.isEmail(jdata['email']):
         return self.setError(scode, AllError.InvalidEmailFormat)
     appId, scode = self.appToken.parseApp(jdata['appToken'])
     err = self.appToken.checkScode(scode)
     if err != AllError.ok:
         return self.setError(scode, err)
     if self.userAuthRepository.findEmail(scode, jdata['email']):
         return self.setError(scode, AllError.ExistEmail)
     return self.__registerUser(scode, EUserAuthType.email, jdata, False)
Exemplo n.º 9
0
    def create(self, scode, userId, uuid, authType):
        expireAt = datetime.now() + timedelta(days=self.EXPIRE_DAYS)
        expireAt = expireAt.strftime('%Y-%m-%d %H:%M:%S')

        tokenId = StrUtils.getMapleUuid('tokenId:')
        token = CryptoHelper.encrypt(scode + chr(31) + userId + chr(31) +
                                     uuid + chr(31) + str(authType) + chr(31) +
                                     expireAt) + '-' + str(
                                         int(datetime.now().timestamp()))

        return tokenId, token
Exemplo n.º 10
0
    def create(self, scode, userId, userName, uuid, loginTokenId):
        #expireAt = datetime.now() + timedelta(days=self.EXPIRE_DAYS)
        startAt = datetime.now().strftime('%Y-%m-%d %H:%M:%S')

        tokenId = StrUtils.getMapleUuid('tokenId:')
        token = CryptoHelper.encrypt(tokenId + chr(31) + loginTokenId +
                                     chr(31) + scode + chr(31) + userId +
                                     chr(31) + userName + chr(31) + uuid +
                                     chr(31) + startAt)

        return tokenId, token
Exemplo n.º 11
0
    def registerMobile(self, scode, jdata):
        if StrUtils.isPhone(jdata['mobile']):
            return self.setError(scode, AllError.InvalidMobileFormat)
        appId, scode = self.appToken.parseApp(jdata['appToken'])
        err = self.appToken.checkScode(scode)
        if err != AllError.ok:
            return self.setError(scode, err)

        if self.userAuthRepository.findMobile(scode, jdata['mobile']):
            return self.setError(scode, AllError.ExistPhoneNo)
        return self.__registerUser(scode, EUserAuthType.mobile, jdata, False)
Exemplo n.º 12
0
    def addReply(self, scode, session, jdata):
        userId = session['userId']
        boardId = jdata['boardId']
        replyId = StrUtils.getMapleUuid('replyId:')

        if ('parentReplyId' not in jdata or len(jdata['parentReplyId']) < 1) and ('depth' not in jdata or int(jdata['depth']) > 0):
            return self.setError(scode, AllError.ErrorReplyHierarchy)

        self.boardReplyRepository.insert(scode, replyId, boardId, jdata['parentReplyId'], userId, session['userName'], jdata['depth'], jdata['body'])
        replyList = self.boardReplyRepository.getList(scode, boardId, 0, 15)

        return self.setOk(scode, {'replyId': replyId, 'replyList': replyList})
Exemplo n.º 13
0
    def addVote(self, scode, session, jdata):
        if len(jdata['voteItems']) < 2:
            return self.setError(scode, AllError.VoteItemHas2More)
        res = self.addBoard(scode, session, jdata)
        if res['result'] != 'ok':
            return res
        userId = session['userId']
        boardId = res['data']['boardId']

        if self.boardVoteRepository.insert(scode, boardId, userId, session['userName'], jdata['expiredAt']) == False:
            self.boardRepository.deleteBoard(scode, boardId, userId)
            return self.setError(scode, AllError.InvalidParameter)        
        for voteItem in jdata['voteItems']:
            voteId = StrUtils.getMapleUuid('voteId:')
            self.boardVoteItemRepository.insert(scode, boardId, voteId, voteItem)        
        return self.setOk(scode, {'boardId': boardId})
Exemplo n.º 14
0
 def __checkAdminToken(self, jdata, passwd=False):
     if 'token' not in jdata:
         return self.setError('admin', AllError.InvalidAdminToken)
     token = self.adminToken.parseUser(jdata['token'])
     if token == None:
         return self.setError('admin', AllError.InvalidAdminToken)
     if self.adminToken.isExpired(token['expireAt']) == True:
         return self.setError('admin', AllError.ExpiredAdminToken)
     if self.adminTokenRepository.isAvailableToken(token['userId'],
                                                   jdata['token']) == False:
         return self.setError('admin', AllError.UnauthorizedOrExpiredUser)
     if passwd:
         user = self.adminUserRepository.getUserByUserIdPassword(
             token['userId'], StrUtils.getSha256(jdata['password']))
         if user is None:
             return self.setError('admin', AllError.UnauthorizedUser)
     return token
Exemplo n.º 15
0
    def addMessage(self, scode, session, jdata):
        userId = session['userId']
        channelId = jdata['channelId']
        msgId = StrUtils.getMapleUuid('msgId:')

        if self.msgRepository.insert(scode, msgId, channelId, userId,
                                     jdata['messageType'],
                                     jdata['content']) == False:
            return self.setError(AllError.FailToSaveMessage)
        if self.channelRepository.updateLastMsgAndTime(
                scode, channelId,
                self._getShortContent(jdata['content'])) == False:
            return self.setError(AllError.FailToUpdateChannel)
        return self.setOk(scode, {
            'messageId': msgId,
            'content': jdata['content']
        })
Exemplo n.º 16
0
    def cropImageByFullPath(self, scode, userId, srcPath, destPath):
        if StrUtils.isImageFile(srcPath) == False:
            return False
        path = os.path.join(destPath, scode, userId)
        if os.path.exists(path) == False:
            os.makedirs(path)
        filename = srcPath.split('/')[-1]
        destPath = os.path(path, filename)

        im = Image.open(srcPath)
        w, h = im.size

        left = (w - self.IMAGE_CROP_SIZE)/2 if w > self.IMAGE_CROP_SIZE else 0
        right = left + self.IMAGE_CROP_SIZE
        top = (h - self.IMAGE_CROP_SIZE)/2 if h > self.IMAGE_CROP_SIZE else 0
        bottom = top + self.IMAGE_CROP_SIZE

        im1 = im.crop((left, top, right, bottom))
        im1.save(destPath)
        return True
Exemplo n.º 17
0
 def channelCreate(self, scode, session, jdata):
     userId = session['userId']
     attendeeCount = 2
     if len(jdata['attendees']) > 1:
         jdata['attendees'].append(userId)
         attendeeCount += 1
     else:
         channelRec = self.channelRepository.findChannel(
             scode, userId, jdata['attendees'][0])
         if channelRec != None:
             self.myChannelRepository.insert(scode, userId,
                                             channelRec['channelId'])
             return self.setOk(scode, channelRec['channelId'])
     channelId = StrUtils.getMapleUuid('channelId:')
     attendees = '|'.join([attendee for attendee in jdata['attendees']])
     self.channelRepository.insert(
         scode, channelId, userId, jdata['channelName'], attendees,
         len(attendees), EChannelType.oneToOne.name
         if attendeeCount == 2 else EChannelType.group.name)
     self.myChannelRepository.insert(scode, userId, channelId)
     return self.setOk(scode, {'channelId': channelId})
Exemplo n.º 18
0
    def __uploadFile(self, ):
        fileId = StrUtils.getMapleUuid('fileId:')


#     def download(self, scode, userId, url, savePath):
#         if url is None:
#             return None, None
#         filename = (str(int(datetime.now().microsecond / 1000)))+'-'+ url.split('/')[-1]
#         path = os.path.join(savePath, scode, userId)
#         if os.path.exists(path) == False:
#             os.makedirs(path)
#         savePath = os.path.join(path, filename)

#         r = requests.get(url, allow_redirects=True)
#         open(savePath, 'wb').write(r.content)

#         return savePath, os.stat(savePath).st_size

#     private String uploadFile(MultipartFile file, String scode, String userName, String uploadDir, String serverIp, String comment) {
#         String fileId = StrUtils.getUuid("file");
#         Path savePath = Paths.get(uploadDir, scode, fileId);

#         try {
#             file.transferTo(savePath);
#         } catch (IOException e) {
#             return null;
#         }

#         List<String> queries = new ArrayList<>();

#         String userId = userCommonRepository.findUserIdByUserName(scode, userName);
#         Long fileSize = file.getSize();
#         EUploadFileType eType = EUploadFileType.getType(FileUtils.getFileExt(file.getOriginalFilename()));;
#         queries.add(fileCommonRepository.queryInitFileInfo(scode, fileId, userId, serverIp, userName, eType.getValue(), fileSize, comment));

#         ImageUtil.ImageSize imageSize = null;
#         try {
#             imageSize = ImageUtil.getImageSize(new File(savePath.getFileName().toString()));
#         } catch (IOException e) {
#             return null;
#         }
#         queries.add(fileCommonRepository.queryUpdateFileInfo(scode, fileId, imageSize.getWidth(), imageSize.getWidth(), fileSize));

#         float rate = imageSize.getWidth() > imageSize.getHeight()? FileConfig.THUMB_SIZE / (float)imageSize.getWidth() : FileConfig.THUMB_SIZE / (float)imageSize.getHeight();
#         String thumbName = newThumbFilename();
#         int thumbWidth = (int)(imageSize.getWidth() * rate);
#         int thumbHeight = (int)(imageSize.getHeight() * rate);
#         String thumbFilePath = getThumbPath(scode, thumbName);

#         imageResizeWorker.doResize(savePath.toString(), thumbFilePath, thumbWidth, thumbHeight, new ImageResizeWorker.ImageResizerCallback() {
#             @Override
#             public void onCompleted(Object dest) {
#                 log.error("Completed - " + dest);
#             }

#             @Override
#             public void onFailed(Object src) {
#                 log.error("Failed - " + src);
#             }
#         });
#         queries.add(fileCommonRepository.queryUpdateThumbnail(scode, fileId, thumbName, thumbWidth, thumbHeight));
#         fileCommonRepository.multiQueries(scode, queries);
#         return fileId;
#     }

#     private static int seq = 0;
#     private String newThumbFilename() {
#         return String.format("%s%d_%03d", FileConfig.THUMB_PATH, System.currentTimeMillis(), ++seq % 1000);
#     }

#     private String getThumbPath(String scode, String fileName) {
#         return Paths.get(FileConfig.UPLOADED_FOLDER, scode, FileConfig.THUMB_PATH, fileName).toString();
#     }

#   ICommandFunction<AuthSession, ResponseData<EAllError>, FileForm.UploadForm> doUploadFile = (AuthSession authSession, ResponseData<EAllError> res, FileForm.UploadForm form) -> {
#         List<FileResult> fileIds = new ArrayList<>();
#         String fileId = uploadFile(form.getMultipartFile(), form.getScode(), form.getUserName(), form.getUploadDir(), form.getServerIp(), form.getComment());
#         fileIds.add(new FileForm().new FileResult(form.getMultipartFile().getOriginalFilename(), fileId));
#         res.setParam("fileIds", fileIds);
#         return res.setError(EAllError.ok);
#     };

#     ICommandFunction<AuthSession, ResponseData<EAllError>, FileForm.MultiUploadForm> doMultiUploadFile = (AuthSession authSession, ResponseData<EAllError> res, FileForm.MultiUploadForm form) -> {
#         List<MultipartFile> files = form.getMultipartFiles();
#         List<FileResult> fileIds = new ArrayList<>();
#         for(MultipartFile file : files) {
#             String fileId = uploadFile(file, form.getScode(), form.getUserName(), form.getUploadDir(), form.getServerIp(), form.getComment());
#             fileIds.add(new FileForm().new FileResult(file.getOriginalFilename(), fileId));
#         }
#         res.setParam("fileIds", fileIds);
#         return res.setError(EAllError.ok);
#     };
Exemplo n.º 19
0
    def userLogin(self, scode, jdata):
        appId, scode = self.appToken.parseApp(jdata['appToken'])

        auth = self.userAuthRepository.getUserByUserName(scode, jdata['userName'])
        if auth == None:
            return self.setError(scode, AllError.NotExistUserAuth)

        if EUserAuthType(auth['authType']) == EUserAuthType.idpw and auth['password'] != StrUtils.getSha256(jdata['password']):
            return self.setError(scode, AllError.InvalidUser)
        
        userId = auth['userId']
        uuid = jdata['uuid']
        tokenRec = self.userTokenRepository.getTokenByUserId(scode, userId)
        if tokenRec == None:
            return self.setError(scode, AllError.UnauthorizedUserId)

        tokenId, token = self.loginToken.create(scode, userId, uuid, auth['authType'])  #로그인하면 로그인토큰을 매번 갱신한다.
        result = False
        if tokenRec['uuid'] == uuid:
            result = self.userTokenRepository.updateToken(scode, userId, uuid, tokenId, token, True)
        else:
            queries = []
            queries.append(self.userTokenRepository.qDeleteTokenByUuid(scode, userId, uuid))
            queries.append(self.userTokenRepository.qInsertToken(scode, userId, uuid, tokenId, token, True))
            result = self.userRepository.multiQueries(scode, queries)
        if result == False:
            return self.setError(scode, AllError.FailedUpdateToken)
        
        self.userPushRepository.insert(scode, userId, uuid, jdata['epid'] if 'epid' in jdata else '')
        self.userRepository.updateUserDetail(scode, userId, 
                jdata['osType'] if 'osType' in jdata else '', 
                jdata['osVersion'] if 'osVersion' in jdata else '', 
                jdata['appVersion']if 'appVersion' in jdata else '')
        return self.setOk(scode, {'loginToken': token})