コード例 #1
0
def updateTelevision(bot, job):
    logger.info(__name__, "Updating television database...")
    shows = sonarr.getAllShows()
    if (shows is not None):
        # Add any new TV series to the database
        for show in shows:
            insert.insertTV(show[0], show[1])
        # Compare and delete removed shows from database to Sonarr
        shows_inactive = constants.listDifference(select.getDatabaseShows(),
                                                  shows)
        if (len(shows_inactive) > 0):
            show_ids = sonarr.getAllShowIDs()
            for show in shows_inactive:
                if (show[0] in show_ids):
                    update.updateTV(show[0], show[1])
                else:
                    delete.deleteTV(show[0])
                logger.warning(
                    __name__,
                    "Television series '{}' has been modified in the database".
                    format(show[1]))
        logger.info(__name__, "Finished updating television database")
    else:
        logger.warning(
            __name__,
            "Failed to update television database. Will try again at next scheduled run"
        )
コード例 #2
0
ファイル: views.py プロジェクト: git-kessededieu/phytorganic
def check_balance(request):
    form = request.POST.get("form", None)
    payment_mode = request.POST.get('payment_mode', None)
    data = {}

    if form is not None:
        form_data = str_to_json(form)
        pack = form_data.get('pack', None)

        grade = Pack.objects.filter(id = int(pack)).first()
        if grade is not None:
            try:
                member_wallet = MemberWallet.objects.get(member__user = request.user)
                if payment_mode == "wallet1":
                    member_wallet = member_wallet.wallet1
                else:
                    member_wallet = member_wallet.wallet2

                if member_wallet >= grade.price:
                    data["status"] = "success"
                    data["message"] = _("You can process your order")
                else:
                    data["status"] = "warning"
                    data["message"] = _("Your Wallet balance is not sufficient to complete this order !!!")
            except MemberWallet.DoesNotExist as e:
                logger.warning(request, e)
                data["status"] = "warning"
                data["message"] = _("User's wallet don't exist")
        else:
            data["status"] = "error"
            data["message"] = _("No data submitted")

    return JsonResponse(data)
コード例 #3
0
def updateMovies(bot, job):
    logger.info(__name__, "Updating movies database...")
    movies = radarr.getAllMovies()
    if (movies is not None):
        # Add any new movies to the database
        for movie in movies:
            insert.insertMovie(movie[0], movie[1])
        # Compare and delete removed movies from database to Radarr
        movies_inactive = constants.listDifference(select.getDatabaseMovies(),
                                                   movies)
        if (len(movies_inactive) > 0):
            movie_ids = radarr.getAllMovieIDs()
            for movie in movies_inactive:
                if (movie[0] in movie_ids):
                    update.updateMovie(movie[0], movie[1])
                else:
                    delete.deleteMovie(movie[0])
                logger.warning(
                    __name__,
                    "Movie '{}' has been modified the database".format(
                        movie[1]))
        logger.info(__name__, "Finished updating movie database")
    else:
        logger.warning(
            __name__,
            "Failed to update movie database. Will try again at next scheduled run"
        )
コード例 #4
0
 def run(self):
     for tile in self.tiles:
         name = '{0}/{1}/{2}.png'.format(*tile)
         try:
             data = self.tm.tile(tile)
         except DownloadError:
             logger.warning("Failed to download tile %s" % name)
         else:
             self.zipfile.writestr(name, data)
     self.zipfile.close()
コード例 #5
0
ファイル: sonarr.py プロジェクト: lad1337/Plex-Assistant-Bot
def getShowInfo(id):
    try:
        payload = {'term': 'tvdb:' + str(id), 'apikey': api}
        request = requests.get(host + constants.SONARR_SERIES_LOOKUP,
                               params=payload)
        if (request.status_code is not 200):
            raise Exception()
        return (request.json())
    except:
        logger.warning(
            __name__,
            "Could not fetch series info from Sonarr (status code {})".format(
                request.status_code))
コード例 #6
0
def getMovieInfo(id):
    try:
        payload = {'tmdbId': str(id), 'apikey': api}
        request = requests.get(host + constants.RADARR_MOVIES_LOOKUP,
                               params=payload)
        if (request.status_code is not 200):
            raise Exception()
        return (request.json())
    except:
        logger.warning(
            __name__,
            "Could not fetch series info from Radarr (status code {})".format(
                request.status_code))
コード例 #7
0
ファイル: config.py プロジェクト: lad1337/Plex-Assistant-Bot
def parseAdmins():
    try:
        if ('TELEGRAM' in parser):
            for admin in parser['TELEGRAM']['AUTO_ADMINS'].split(','):
                telegram.addAdmin(int(admin.strip()))
                logger.warning(__name__,
                               "Telegram admins: {}".format(telegram.admins))
        else:
            raise Exception()
    except:
        logger.error(
            __name__,
            "Failed to get the admin user list: Check your config.ini")
        exit()
コード例 #8
0
ファイル: sonarr.py プロジェクト: lad1337/Plex-Assistant-Bot
def getAllShowIDs():
    try:
        payload = {'apikey': api}
        request = requests.get(host + constants.SONARR_SERIES, params=payload)
        if (request.status_code is not 200):
            raise Exception()
        shows = []
        for show in request.json():
            shows.append(show['tvdbId'])
        return shows
    except:
        logger.warning(
            __name__,
            "Could not fetch series list from Sonarr (status code {})".format(
                request.status_code))
コード例 #9
0
ファイル: config.py プロジェクト: lad1337/Plex-Assistant-Bot
def parseNotifications():
    try:
        if ('NOTIFICATIONS' in parser):
            constants.NOTIFICATION_TIME = parser['NOTIFICATIONS']['TIME']
            constants.NOTIFICATION_DAY = parser['NOTIFICATIONS']['DAY']
            logger.warning(
                __name__, "Notification times set: {} @ {}".format(
                    constants.NOTIFICATION_DAY, constants.NOTIFICATION_TIME))
        else:
            raise Exception()
    except:
        logger.error(
            __name__,
            "Failed to get notification times: Check your config.ini")
        exit()
コード例 #10
0
def getAllMovieIDs():
    try:
        payload = {'apikey': api}
        request = requests.get(host + constants.RADARR_MOVIES, params=payload)
        if (request.status_code is not 200):
            raise Exception()
        movies = []
        for movie in request.json():
            movies.append(movie['tmdbId'])
        return movies
    except:
        logger.warning(
            __name__,
            "Could not fetch series list from Radarr (status code {})".format(
                request.status_code))
コード例 #11
0
def start():
    # Initialize all the things
    logger.initialize()
    config.initialize()
    table.initialize()
    handlers.initialize()
    jobs.initialize()
    server.initialize()
    # If it got here, it means that everything has initialized correctly so the bot is about to start
    logger.warning(
        "main.start",
        "{} ({}: @{}) has started!".format(constants.BOT_NAME,
                                           telegram.updater.bot.id,
                                           telegram.updater.bot.username))
    telegram.updater.start_polling()
    telegram.updater.idle()
コード例 #12
0
def startServer():
    # Starts the server on a seperate thread since it is an infinite loop waiting for connections
    server_thread = Thread(target=serverListen)
    server_thread.start()
    logger.warning(__name__, "Notification listener running: {}:{}".format(constants.SOCKET_HOST, constants.SOCKET_PORT))
コード例 #13
0
ファイル: auth.py プロジェクト: marcuslacerda/ciandt-stack
    def post(self):
        """Autenticate google user account.

        Expect a request json with clientId, redirectUri and code attributes.
        Samples:
         {
         'clientId': your-google-client-id,
         'code': '4/xHYKb3CD9gbiXBiL2XPaj_ILlMjXTJbVmBTFCVGBjKo',
         'accessType': 'offline',
         'redirectUri': u'http://localhost:8080'
         }

        """
        access_token_url = 'https://www.googleapis.com/oauth2/v4/token'
        people_api_url = 'https://www.googleapis.com/oauth2/v3/userinfo'
        tokeninfo_url = 'https://www.googleapis.com/oauth2/v3/tokeninfo'

        logger.debug('google request =>')
        logger.debug(request.json)

        payload = dict(client_id=request.json['clientId'],
                       redirect_uri=request.json['redirectUri'],
                       client_secret=app.config['GOOGLE_CLIENT_SECRET'],
                       code=request.json['code'],
                       grant_type='authorization_code')

        logger.debug('Google Payload =>')
        logger.debug(payload)

        # Step 2. Exchange authorization code for access token.
        r = requests.post(access_token_url, data=payload)
        token = json.loads(r.text)
        logger.debug('Access Token =>')
        logger.debug(token)

        # Step 2. Retrieve information about the current user.

        headers = {'Authorization': 'Bearer {0}'.format(token['access_token'])}
        r = requests.get(people_api_url, headers=headers)
        profile = json.loads(r.text)
        logger.info('Login as => %s' % profile['email'])
        logger.debug(profile)

        if security.is_valid_email(profile['email']):
            # Step 4. Create a new account or return an existing one.
            r = requests.get('%s?access_token=%s' % (tokeninfo_url, token['access_token']))
            token_info = json.loads(r.text)
            logger.debug('Tokeninfo =>')
            logger.debug(token_info)

            # Step 5. Sign-up a user process
            account = {}
            try:
                account = repository.get_document(
                    index=index,
                    doc_type=doc_type,
                    id=profile['sub'])

                # update refresh_token if it was informed (after revoke token)
                logger.debug('Account found for %s' % profile['email'])
                if 'refresh_token' in token:
                    logger.debug('A new refresh_token was defined. It will be updated')
                    repository.update(
                        index=index,
                        doc_type=doc_type,
                        id=profile['sub'],
                        body={"doc": {"refresh_token":  token['refresh_token']}}
                    )
                # if extits, profile will be the accound founded

                # profile['refresh_token'] = account["_source"]['refresh_token']
            except NotFoundError as e:
                # create a new user if not exists one account
                logger.warning('First logging for  %s' % profile['email'])

                account = profile.copy()
                account['created_at'] = datetime.utcnow()

                if 'refresh_token' in token:
                    account['refresh_token'] = token['refresh_token']

                repository.insert(index=index, doc_type=doc_type, login=account['sub'], document=account)

            # Step 6. Build and return a json web token.
            jwt_payload = {
                'sub': profile['sub'],
                'iat': datetime.utcnow(),
                'exp': datetime.utcnow() + timedelta(days=5),
                'access_token':token['access_token'],
                'user': profile
            }

            jwt = security.create_token(jwt_payload)
            return jsonify(token=jwt)
            # return jsonify(token=token['access_token'])
        else:
            return security.response_not_authorized(
                403,
                'Invalid email domain. Please sign with ciandt.com acccount'
                )
コード例 #14
0
def exit():
    server.stopServer()
    logger.warning("main.start",
                   "Successfully closed {}!".format(constants.BOT_NAME))