コード例 #1
0
ファイル: app.py プロジェクト: einalex/todo
    def push(self):
        """Push todo to gist.github.com"""
        github = Github()
        gist_id = GistId().get()
        token = GithubToken().get()

        github.login(token)

        if not self.todo.name:
            name = "Todo"
        else:
            name = self.todo.name

        files = {
            name: {
                "content": self.todo_content
            }
        }

        log.info(
            "Pushing '%s' to https://gist.github.com/%s .." % (name, gist_id)
        )
        response = github.edit_gist(gist_id, files=files)

        if response.status_code == 200:
            log.ok("Pushed success.")
        elif response.status_code == 401:
            log.warning("Github token out of date, empty the old token")
            GithubToken().save('')  # empty the token!
            self.push()  # and repush
        else:
            log.error("Pushed failed. %d" % response.status_code)
コード例 #2
0
ファイル: app.py プロジェクト: einalex/todo
    def get(self):
        """
          call this method to get a token::

            token = GithubToken().get()

          what the get() does:
            1) read from "~/.todo/token"
            2) check if the token read is empty.
               (yes)-> 1) if empty,
                          ask user for user&passwd to access api.github.com
                        2) fetch the token, set to this instance and store it.
            3) return the token (a string)
        """
        if self.is_empty:
            user = ask_input.text("Github user:"******"Password for %s:" % user)

            log.info("Authorize to github.com..")
            response = Github().authorize(user, password)

            if response.status_code == 201:
                # 201 created
                log.ok("Authorized success.")
                # get token from dict
                token = response.json()["token"]
                self.save(token)
            else:
                log.error("Authorization failed. %d" % response.status_code)
        return self.content
コード例 #3
0
ファイル: app.py プロジェクト: einalex/todo
    def pull(self, name=None):
        """Pull todo from remote gist server"""

        if not name:  # if not name figured out
            if self.todo.name:
                name = self.todo.name  # use the todo.txt's name
            else:
                log.error("Please tell me todo's name to pull.")

        github = Github()
        gist_id = GistId().get()

        resp = github.get_gist(gist_id)

        if resp.status_code != 200:
            log.error("Pull failed.%d" % resp.status_code)

        dct = resp.json()  # get out the data

        u_name = name.decode("utf8")  # decode to unicode

        # Note that data back from github.com is unicode
        if u_name not in dct["files"]:
            log.error("File '%s' not in gist: %s" % (name, gist_id))

        u_url = dct["files"][u_name]["raw_url"]
        url = u_url.encode("utf8")

        response = requests.get(url)

        if response.status_code == 200:
            todo_content = response.text.encode("utf8")
            self.todo_txt.write(todo_content)
            log.ok("Pulled success to file '%s'" % self.todo_txt.path)
        else:
            log.error("Failed to pull file from %s" % url)
コード例 #4
0
from env_var import *

from models import DNACenter, LocalDatabase, Github

DNACenterLab = DNACenter(username=DNAC_USER,
                         password=DNAC_PASS,
                         base_url=DNAC_URL,
                         name="Lab")
DNACenterProd = DNACenter(username=DNAC_USER_PROD,
                          password=DNAC_PASS_PROD,
                          base_url=DNAC_URL_PROD,
                          name="Prod")
db = LocalDatabase(cluster=Cluster1,
                   database=Database1,
                   collection=Collection1)
github = Github(base_url=GITHUB_URL, token=GITHUB_TOKEN)


def sync_templates(templates):
    """
    The template content is compared between: Github, DNA Center Lab and DNA Center Prod
    The sync status is updated in the database
    """
    for template_name in templates:
        print(template_name)
        try:
            project_name = db.collection.find({"name": template_name
                                               })[0]["projectName"]
        except:
            project_name = template_name["projectName"]
            template_name = template_name["name"]
コード例 #5
0
def get_github_link(bot, update, user_data, job_queue):
    user = update.message.from_user
    logger.debug("user: %s  bye bye! after submit a github link",
                 user.first_name)
    update.message.reply_text(
        u' با تشکر بعد از بررسی لینک داخل کانال @channel گذاشته میشه\n'
        u'و همچنین برای تمای کاربرا ارسال میشه تا بعد از تاییدشون ستاره بگیری برای شر.ع دوباره /start رو بزن',
        reply_markup=ReplyKeyboardRemove())

    message = update.message.text
    logger.debug("message %s", message)

    if "github.com" in message:
        link = message
        temp_list = message.split("/")
        logger.debug("temp %s", temp_list)
        if temp_list[-1] == "":
            temp_list.pop()
        logger.debug("temp %s", temp_list)

        repo_name = temp_list[-1]
        repo_owner = temp_list[-2]

        logger.debug("github_obj.repo_name %s", repo_name)
        logger.debug("github_obj.repo_owner %s", repo_owner)

        logger.info("user: %s send a github link: %s", user.first_name,
                    message)

    else:
        repo_owner, repo_name = message.split(":")
        link = SitePrefix.GITHUB + "/" + repo_owner + "/" + repo_name
        logger.info("user: %s send a github owner: %s repo: %s",
                    user.first_name, repo_owner, repo_name)

    github_obj = Github.get_or_none(owner_id=user_data['id'],
                                    link=link,
                                    repo_name=repo_name,
                                    repo_owner=repo_owner)
    if not github_obj:
        github_obj = Github.create(owner_id=user_data['id'],
                                   link=link,
                                   repo_name=repo_name,
                                   repo_owner=repo_owner)
    github_obj.save()
    logger.debug("github object saved")

    after = 1
    user_data['jobs'] = []
    for _secret in Secret.select().where(Secret.permitted == True):
        context = {
            "token": _secret.secret,
            "chat_id": user.id,
            "secret_owner_chat_id": _secret.owner.uid,
            "repo_name": repo_name,
            "repo_owner": repo_owner,
            "try": 0
        }
        job = job_queue.run_once(set_star, after, context=context)

        user_data['jobs'].append({"job": job, "context": context})
        after += Const.REQUEST_DELAY

        logger.info("secret owner name: %s staring owner: %s repo: %s",
                    _secret.owner.first_name, github_obj.repo_owner,
                    github_obj.repo_name)

    return ConversationHandler.END
コード例 #6
0
ファイル: app.py プロジェクト: einalex/todo
    def get(self, answer=None):  # add answer to figure which approach to go
        """
        call this method to get a gist_id::
            gist_id = GistId().get()
        what the get() dose:
          1) read the gist_id from file "~/.todo/gist_id"
          2) check if the gist_id if empty
             (yes)-> 1) if the gist_id is empty, ask user to input it or
                     new a gist directly.
                     2) save the new gist_id
          3) return the gist_id
        """

        if self.is_empty:
            print "Tell me the gist's id you want to push to:"
            print " 1. New a gist right now."
            print " 2. Let me input a gist's id."
            if answer is None:
                answer = ask_input.text("Input your answer(1/2):")
            if answer == '2':
                self.save(ask_input.text("Gist id:"))
            elif answer == '1':
                # new a gist
                todo_content = TodoTxt().read()
                todo = parser.parse(todo_content)
                if not todo.name:
                    name = "Todo"
                else:
                    name = todo.name

                files = {
                    name: {
                        "content": todo_content
                    }
                }

                resp = None

                github = Github()
                token = GithubToken().get()
                github.login(token)  # need to login
                log.info("Create a new gist..")
                resp = github.create_gist(files=files, description="Todo")

                if resp.status_code == 201:
                    dct = resp.json()
                    html_url = dct["html_url"].encode("utf8")
                    log.ok("Create success:%s ,"
                           "pushed at file '%s'" % (html_url, name))
                    self.save(dct["id"])
                    sys.exit()
                elif resp.status_code == 401:
                    log.warning("Github access denied, empty the old token")
                    GithubToken().save('')  # empty the token!
                    # and re create
                    self.get(answer='1')
                else:
                    log.error("Create gist failed. %d" % resp.status_code)
            else:  # exit if else input
                log.error("Invalid answer.")
        return self.content