Esempio n. 1
0
def getHtml(urlNum, allUrlList, urlImgQueue, urlQueue):
    while (urlNum < 20 and urlQueue.not_empty):
        url = urlQueue.get()

        thisHtml = Html(url)
        html = thisHtml.getHtml()

        if (html != None):
            thisUrl = Url(html, allUrlList, urlQueue, urlImgQueue, urlNum)
            allUrlList, urlQueue, urlImgQueue, urlNum = thisUrl.getUrl()
Esempio n. 2
0
 def sms_confirm(self, username, password):
     resp = self.session.post(Url.login(),
                              data=json.dumps(data),
                              headers={'Content-Type': 'application/json'})
     resp = self.session.post(Url.challenge(c_id),
                              data=json.dumps(data_resp),
                              headers={'Content-Type': 'application/json'})
     resp = self.session.post(Url.login(),
                              data=json.dumps(data),
                              headers={
                                  'Content-Type': 'application/json',
                                  'X-ROBINHOOD-CHALLENGE-RESPONSE-ID': c_id
                              })
Esempio n. 3
0
 def account_info(self):
     if not self.logged_in:
         return None
     resp = self.session.get(Url.accounts())
     if Client.DEBUG:
         Client.log_response(resp)
     return json.loads(resp.text)
Esempio n. 4
0
    def sell(self, symbol, quantity, extended=False, cancel=None):
        if not self.logged_in:
            self.prompt_login()
        # This also updates stock_ids
        symbol = symbol.upper()
        instrument = self.get_instrument(symbol)
        if cancel is None:
            cancel = "gfd"
        price = float(self.get_quote(symbol).price)

        data = {
            "time_in_force": cancel,
            "price": "{0:.2f}".format(price),
            "quantity": quantity,
            "side": "sell",
            "trigger": "immediate",
            "type": "market",
            "account": self.account['url'],
            "instrument": instrument,
            "symbol": symbol,
            # "ref_id":"",
            "extended_hours": extended
        }
        if Client.DEBUG:
            print(data)

        resp = self.session.post(Url.order(),
                                 data=json.dumps(data),
                                 headers={'Content-Type': 'application/json'})
        self.pending_orders.append(json.loads(resp.text))
        if Client.DEBUG:
            Client.log_response(resp)
Esempio n. 5
0
def main():
    #Defining Variables
    covers_url = 'https://www.covers.com/Sports/mlb/PrintSheetHtml?isPrevious=False'
    urlObj = Url(covers_url)
    parser = Parser()

    #Logic
    bs_obj = urlObj.getBSoup()

    oddTable = bs_obj.findAll('tr', attrs={'class': 'trBackGround'})
    evenTable = bs_obj.findAll('tr', attrs={'class': ''})

    #oddThread and evenThreads are list of lists DS.
    #which contains the game threads
    oddThreads = parser.parseTable(oddTable)
    evenThreads = parser.parseTable(evenTable)
Esempio n. 6
0
def main():
    u = Url()
    m = Message()

    last_update_id = ''

    while True:
        print("Updates")
        updates = u.get_updates(last_update_id)

        print(updates)

        if len(updates['result']) > 0:
            last_update_id = m.get_last_update_id(updates) + 1
            m.handle_updates(updates)

        time.sleep(0.5)
Esempio n. 7
0
class ParserUrls:
    name = 'ParseUrls'

    def __init__(self, site, url, postfix=''):
        self.url = Url(site, url, postfix)

    def parse(self, reg, range_postfix):
        bodies = []
        start, end = tuple(range_postfix)
        for i in tqdm(range(start, end), desc=f'{self.name}'):
            url = self.url.link(i)
            text = Text.create_by_url(url)
            bodies_sub = text.findall(reg)
            bodies.extend(bodies_sub)

        urls = self.url.concat_site_with_bodies(bodies)
        return urls
Esempio n. 8
0
 def __init__(self, username):
     username = username.lower().strip()
     userdb = db.query_db("select * from users where username = ?", [username])
     if len(userdb) == 0:
         raise Exception("No user '%s' found" % (username))
     self.username = userdb[0]["username"]
     self.logins = userdb[0]["logins"]
     self.last_login = userdb[0]["last_login"]
     self.urlcount = len(Url.get_all(self.username))
Esempio n. 9
0
 def get_quote(self, symbol):
     symbol = symbol.upper()
     self.get_instrument(symbol)
     # stock_ids is updated
     s_id = self.stock_ids[symbol]
     resp = self.session.get(Url.quote(s_id))
     if Client.DEBUG:
         Client.log_response(resp)
     return Quote(json.loads(resp.text))
Esempio n. 10
0
 def get_book(self, symbol):
     if not self.logged_in:
         return None
     symbol = symbol.upper()
     self.get_instrument(symbol)
     resp = self.session.get(Url.book(self.stock_ids[symbol]))
     if Client.DEBUG:
         Client.log_response(resp)
     return json.loads(resp.text)
Esempio n. 11
0
 def logout(self):
     if not self.logged_in:
         return
     data = {"client_id": self.client_id, "token": self.refresh_token}
     resp = self.session.post(Url.logout(),
                              data=json.dumps(data),
                              headers={'Content-Type': 'application/json'})
     if Client.DEBUG:
         Client.log_response(resp)
     self.logged_in = False
Esempio n. 12
0
def new_url():
    slug = request.form["slug"]
    url = request.form["url"]
    print(url, slug)

    if slug == "":
        slug = generateSlug(6)

    urlArr.append(Url(url, slug))
    return "http://localhost:5000/" + slug
Esempio n. 13
0
    def insecure_login(self):
        self.prompt_login()

        resp = self.session.post(Url.login(),
                                 data=json.dumps(data),
                                 headers={'Content-Type': 'application/json'})

        self.logged_in = True
        # make account request to get current info
        self.account = self.account_info()['results'][0]
Esempio n. 14
0
def get_all_files(dev_directory):

    file_count_name = 'indexes2/inverted_index_'
    file_count = 0
    file_count_name_count = 1
    doc_id = 1
    inverted_index = defaultdict(list)
    reader = Html_Reader()
    for direct in os.listdir(dev_directory):

        if direct != '.DS_Store':

            for file in os.listdir(dev_directory + direct):

                # posting(file) returns url and stuff for DOC_ID_DICT and for tokenizer
                temp = Url(dev_directory + direct + '/' + file)
                try:
                    read = reader.read_file(temp.get_html(), doc_id,
                                            inverted_index)
                    if read:
                        # write to a file the current inverted index, if it is above a certain file count
                        file_count += 1
                        DOC_ID_DICT[doc_id] = temp.get_url()
                        doc_id += 1

                except Exception as e:
                    with open('error.txt', 'w+') as error_file:
                        error_file.write(str(e) + str(temp.get_url()) + "\n")
                if file_count == 1000:
                    write_to_index(inverted_index, file_count_name_count,
                                   file_count_name)
                    inverted_index = defaultdict(list)
                elif file_count > 1000:
                    file_count_name_count += 1
                    file_count = 0
                    # adds the current dict to a file for a partial index
                    # change file_count_name also to write to a different file

    write_to_index(inverted_index, file_count_name_count, file_count_name)
    write_doc_ids(DOC_ID_DICT)
Esempio n. 15
0
 def get_instrument(self, symbol):
     if symbol in self.instruments.keys():
         return self.instruments[symbol]
     else:
         resp = self.session.get(Url.instruments(symbol=symbol))
         if Client.DEBUG:
             Client.log_response(resp)
         obj = json.loads(resp.text)
         url = obj['results'][0]['url']
         self.instruments[symbol] = url
         self.stock_ids[symbol] = obj['results'][0]['id']
         self.symbols[obj['results'][0]['id']] = symbol
         return url
Esempio n. 16
0
def create_graph():
    graph = nx.DiGraph()
    dev_directory = "DEV/"
    graph.add_nodes_from(range(1, len(mapping)+1))
    for direct in os.listdir(dev_directory):

            if direct != '.DS_Store':
                
                for file in os.listdir(dev_directory + direct):
                    
                    # posting(file) returns url and stuff for DOC_ID_DICT and for tokenizer
                    temp = Url(dev_directory + direct + '/' + file)
                    if temp.get_url() in mapping:
                        list_of_links = get_all_sublinks(temp.get_html(), temp.get_url())
                        graph.add_edges_from([(mapping[temp.get_url()], final_edge)for final_edge in list_of_links])
                        if mapping[temp.get_url()] == 34480 or mapping[temp.get_url()] == 34479:
    return graph
Esempio n. 17
0
 def get_all(self):
     total4 = 0
     total6 = 0
     totalhits = db.query_db('select sum(hits4) as total4, sum(hits6) as total6 from hits')
     if len(totalhits) > 0:
         total4 = totalhits[0]["total4"]
         total6 = totalhits[0]["total6"]
         if total4 is None:
             total4 = 0
         if total6 is None:
             total6 = 0
     items = {}
     items["Hits"] = total4 + total6
     items["Hit IPv4"] = total4
     items["Hit IPv6"] = total6
     items["URLs"] = Url.total()
     items["Users"] = db.query_db('select count(*) as users from users')[0]["users"]
     return items
Esempio n. 18
0
def authenticateSSO():
    hash = request.args.get('hash')
    validateUrl = request.args.get('validateUrl')
    #return  validateUrl
    data = json.loads(Url.urlRequest(validateUrl).read().decode('utf-8'))
    userData = {
        "uid": data["data"][0]['uid'],
        "uName": data["data"][0]['uName']
    }
    if data["data"][0]["isLive"] == False:
        return redirect(
            __ssoUrl__ +
            '/getNextPage/0/?toast=SSO Session is expired. Please Login again.'
        )

    else:
        newConditions = {"username": "******", "password": "******"}
        params = json.dumps(newConditions).encode('utf8')
        req = urllib.request.Request(
            "http://localhost:8000/auth",
            data=params,
            headers={'content-type': 'application/json'})
        response = urllib.request.urlopen(req)
        data = response.read().decode('utf-8')
        data = json.loads(data)
        resp = jsonify()
        #return data["access_token"]
        #resp.headers("Authorization","JWT "+data["access_token"])
        #resp.location(url_for('protected'))
        r = make_response(redirect('/home'))
        #app.config["Authorization"]="JWT "+data["access_token"].strip()
        #r.headers["Content-Type"]="application/json"
        #r.headers["Authorization"]=app.config["Authorization"].encode('utf-8')
        r.set_cookie('Authorization',
                     str('JWT ' + data["access_token"].strip()),
                     max_age=60 * 30)  #.encode('utf-8'))
        session['uData'] = userData
        #r.headers["Cdd"]="applicatio"
        return r  #edirect('/protected',code=302)
    return jsonify(data["data"][0]["isLive"])
    pass
Esempio n. 19
0
def TestValidator():
    tests = [(True, Url("ftp://ftp.is.co.za/rfc/rfc1808.txt")),
             (True, Url("http://www.ietf.org/rfc/rfc2396.txt")),
             (False, Url("ldap://[2001:db8::7]/c=GB?objectClass?one")),
             (False, Url("mailto:[email protected]")),
             (False, Url("news:comp.infosystems.www.servers.unix")),
             (False, Url("tel:+1-816-555-1212")),
             (False, Url("telnet://192.0.2.16:80/")),
             (False,
              Url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2"))]
    suite = unittest.TestSuite()

    def testcase(expected, value):
        class test(unittest.TestCase):
            def runTest(self):
                self.assertEqual(value.isValid(), expected,
                                 "Url: {}".format(value.url))

        return test()

    for (expected, value) in tests:
        suite.addTest(testcase(expected, value))

    return suite
Esempio n. 20
0
 def __init__(self, site, url, postfix=''):
     self.url = Url(site, url, postfix)
Esempio n. 21
0
 def getItem(self):
     return Item(Request(None,self.method,
     [Header("Content-Type","Content-Type","application/json","text")],
      Url(self.host,self.path)),self.path)   
Esempio n. 22
0
 def delete(self):
     return Item(
         Request(self.auth, "DELETE", self.header,
                 Url(self.urlBase, self.name + "/1")),
         "delete " + self.name)
Esempio n. 23
0
def TestNormalize():
    tests1 = [(False, Url("http://:@example.com/")),
              (False, Url("http://@example.com/")),
              (False, Url("http://example.com")),
              (False, Url("HTTP://example.com/")),
              (False, Url("http://EXAMPLE.COM/")),
              (False, Url("http://example.com/%7Ejane")),
              (False, Url("http://example.com/?q=%C7")),
              (False, Url("http://example.com/?q=%5c")),
              (False, Url("http://example.com/?q=C%CC%A7")),
              (False, Url("http://example.com/a/../a/b")),
              (False, Url("http://example.com/a/./b")),
              (False, Url("http://example.com:80/")),
              (True, Url("http://example.com/")),
              (True, Url("http://example.com/?q=%C3%87")),
              (True, Url("http://example.com/?q=%E2%85%A0")),
              (True, Url("http://example.com/?q=%5C")),
              (True, Url("http://example.com/~jane")),
              (True, Url("http://example.com/a/b")),
              (True, Url("http://example.com:8080/")),
              (True, Url("http://*****:*****@example.com/")),
              (True, Url("ftp://ftp.is.co.za/rfc/rfc1808.txt")),
              (True, Url("http://www.ietf.org/rfc/rfc2396.txt")),
              (True, Url("ldap://[2001:db8::7]/c=GB?objectClass?one")),
              (True, Url("mailto:[email protected]")),
              (True, Url("news:comp.infosystems.www.servers.unix")),
              (True, Url("tel:+1-816-555-1212")),
              (True, Url("telnet://192.0.2.16:80/")),
              (True,
               Url("urn:oasis:names:specification:docbook:dtd:xml:4.1.2")),
              (True, Url("http://127.0.0.1/")),
              (False, Url("http://127.0.0.1:80/")),
              (True, Url("http://www.w3.org/2000/01/rdf-schema#")),
              (False, Url("http://example.com:081/"))]

    suite = unittest.TestSuite()

    def testcase(expected, value):
        class test(unittest.TestCase):
            def runTest(self):
                self.assertTrue(
                    (value.getNormalized() == value.url) == expected)

        return test()

    for (expected, value) in tests1:
        suite.addTest(testcase(expected, value))

    return suite
Esempio n. 24
0
 def search(self):
     return Item(
         Request(self.auth, "GET", self.header,
                 Url(self.urlBase, self.name + "/search")),
         "search " + self.name)
Esempio n. 25
0
 def getAll(self):
     return Item(
         Request(self.auth, "GET", self.header,
                 Url(self.urlBase, self.name + "/")), "list " + self.name)
Esempio n. 26
0
    'Sec-Fetch-User':
    '******',
    'Upgrade-Insecure-Requests':
    '1',
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
    '(KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36'
}
RELEVANT_TITLES = [
    'אחריות', 'דגם', 'זיכרון', 'כונן קשיח', 'משקל', 'סוללה', 'מעבד',
    'מאיץ גרפי'
]
NUMBER_OF_CATALOG_PAGES_TO_SCRAPE = 2

URL = Url(
    "https://ksp.co.il/?select=.268..271..211..5870..2640..347..1798..4517..442..2639.&kg=&list=&sort=2&glist=0&uin=0&txt_search=&buy=&minprice=0&maxprice=0&intersect=&rintersect=&store_real="
)


def run_with_process_pool(
        executor, function,
        *args) -> Coroutine[concurrent.futures.Executor, Callable, List[Any]]:
    """Uses a concurrent.futures.ProcessPoolExecuter to run the parameter 'function'
    with parameters 'args' with a process pool, in parralel.
    returns an awaitable task representing the 'function' running in parralel.

    Args:
        executor (concurrent.futures.ProcessPoolExecuter): executes the process pool
        function (typing.Callable): function to run in parralel
        *args: parameters to pass to function
Esempio n. 27
0
 def getById(self):
     return Item(
         Request(self.auth, "GET", self.header,
                 Url(self.urlBase, self.name + "/1")), "get " + self.name)
Esempio n. 28
0
 def patch(self):
     return Item(
         Request(self.auth, "PATCH", self.header,
                 Url(self.urlBase, self.name + "/1")), "patch " + self.name)
Esempio n. 29
0
class Message:

    str_help = ""
    u = Url()

    def __init__(self):
        self.str_help = """
                         /new NOME DUEDATE
                         /todo ID
                         /doing ID
                         /done ID
                         /delete ID
                         /list
                         /rename ID NOME
                         /dependson ID ID...
                         /duplicate ID
                         /priority ID PRIORITY{low, medium, high}
                         /help
                        """

    @staticmethod
    def get_last_update_id(updates):
        update_ids = []
        for update in updates['result']:
            update_ids.append(int(update["update_id"]))
        return max(update_ids)

    def deps_text(self, task, chat, preceed=''):
        text = ''
        for i in range(len(task.dependencies.split(',')[:-1])):
            line = preceed
            query = db.session.query(Task).filter_by(id=int(
                task.dependencies.split(',')[:-1][i]),
                                                     chat=chat)
            dep = query.one()
            icon = '\U0001F195'
            if dep.status == 'DOING':
                icon = '\U000023FA'
            elif dep.status == 'DONE':
                icon = '\U00002611'
            if i + 1 == len(task.dependencies.split(',')[:-1]):
                line += '└── [[{}]] {} {}\n'.format(dep.id, icon, dep.name)
                line += self.deps_text(dep, chat, preceed + '    ')
            else:
                line += '├── [[{}]] {} {}\n'.format(dep.id, icon, dep.name)
                line += self.deps_text(dep, chat, preceed + '│   ')
            text += line
        return text

    def handle_updates(self, updates):
        def new_assigment(msg, chat):
            duedate = msg.split(' ', 1)[1]
            msg = msg.split(' ', 1)[0]
            task = Task(chat=chat,
                        name=msg,
                        status='TODO',
                        dependencies='',
                        parents='',
                        priority='',
                        duedate=duedate)
            db.session.add(task)
            db.session.commit()
            make_github_issue(task.name, '')
            self.u.send_message(
                "New task *TODO* [[{}]] {} - {}".format(
                    task.id, task.name, task.duedate), chat)

        def rename_assigment(msg, chat):
            text = ''
            if msg != '':
                if len(msg.split(' ', 1)) > 1:
                    text = msg.split(' ', 1)[1]
                    msg = msg.split(' ', 1)[0]
            if not msg.isdigit():
                self.u.send_message("You must inform the task id", chat)
            else:
                task_id = int(msg)
                query = db.session.query(Task).filter_by(id=task_id, chat=chat)
                try:
                    task = query.one()
                except sqlalchemy.orm.exc.NoResultFound:
                    self.u.send_message(
                        "_404_ Task {} not found x.x".format(task_id), chat)
                    return
                if text == '':
                    self.u.send_message(
                        "You want to modify task {}, but you didn't provide any new text"
                        .format(task_id), chat)
                    return
                old_text = task.name
                task.name = text
                db.session.commit()
                self.u.send_message(
                    "Task {} redefined from {} to {}".format(
                        task_id, old_text, text), chat)

        def duplicate_assigment(msg, chat):
            if not msg.isdigit():
                self.u.send_message("You must inform the task id", chat)
            else:
                task_id = int(msg)
                query = db.session.query(Task).filter_by(id=task_id, chat=chat)
                try:
                    task = query.one()
                except sqlalchemy.orm.exc.NoResultFound:
                    self.u.send_message(
                        "_404_ Task {} not found x.x".format(task_id), chat)
                    return
                dtask = Task(chat=task.chat,
                             name=task.name,
                             status=task.status,
                             dependencies=task.dependencies,
                             parents=task.parents,
                             priority=task.priority,
                             duedate=task.duedate)
                db.session.add(dtask)
                for t in task.dependencies.split(',')[:-1]:
                    qy = db.session.query(Task).filter_by(id=int(t), chat=chat)
                    t = qy.one()
                    t.parents += '{},'.format(dtask.id)
                db.session.commit()
                self.u.send_message(
                    "New task *TODO* [[{}]] {}".format(dtask.id, dtask.name),
                    chat)

        def delete_assigment(msg, chat):
            if not msg.isdigit():
                self.u.send_message("You must inform the task id", chat)
            else:
                task_id = int(msg)
                query = db.session.query(Task).filter_by(id=task_id, chat=chat)
                try:
                    task = query.one()
                except sqlalchemy.orm.exc.NoResultFound:
                    self.u.send_message(
                        "_404_ Task {} not found x.x".format(task_id), chat)
                    return
                for t in task.dependencies.split(',')[:-1]:
                    qy = db.session.query(Task).filter_by(id=int(t), chat=chat)
                    t = qy.one()
                    t.parents = t.parents.replace('{},'.format(task.id), '')
                db.session.delete(task)
                db.session.commit()
                self.u.send_message("Task [[{}]] deleted".format(task_id),
                                    chat)

        def todo_assigment(msg, chat):
            id_list = msg.split(" ")
            for id in id_list:
                if not id.isdigit():
                    send_message("You must inform the task id", chat)
                else:
                    task_id = int(id)
                    query = db.session.query(Task).filter_by(id=task_id,
                                                             chat=chat)
                    try:
                        task = query.one()
                    except sqlalchemy.orm.exc.NoResultFound:
                        send_message(
                            "_404_ Task {} not found x.x".format(task_id),
                            chat)
                        return
                    task.status = 'TODO'
                    db.session.commit()
                    send_message(
                        "*TODO* task [[{}]] {}".format(task.id, task.name),
                        chat)

        def doing_assigment(msg, chat):
            id_list = msg.split(" ")
            for id in id_list:
                if not id.isdigit():
                    send_message("You must inform the task id", chat)
                else:
                    task_id = int(id)
                    query = db.session.query(Task).filter_by(id=task_id,
                                                             chat=chat)
                    try:
                        task = query.one()
                    except sqlalchemy.orm.exc.NoResultFound:
                        send_message(
                            "_404_ Task {} not found x.x".format(task_id),
                            chat)
                        return
                    task.status = 'DOING'
                    db.session.commit()
                    send_message(
                        "*DOING* task [[{}]] {}".format(task.id, task.name),
                        chat)

        def done_assigment(msg, chat):
            id_list = msg.split(" ")
            for id in id_list:
                if not id.isdigit():
                    send_message("You must inform the task id", chat)
                else:
                    task_id = int(id)
                    query = db.session.query(Task).filter_by(id=task_id,
                                                             chat=chat)
                    try:
                        task = query.one()
                    except sqlalchemy.orm.exc.NoResultFound:
                        send_message(
                            "_404_ Task {} not found x.x".format(task_id),
                            chat)
                        return
                    task.status = 'DONE'
                    db.session.commit()
                    send_message(
                        "*DONE* task [[{}]] {}".format(task.id, task.name),
                        chat)

        def list_assigment(msg, chat):
            a = ''
            a += '\U0001F4CB Task List\n'
            query = db.session.query(Task).filter_by(
                parents='', chat=chat).order_by(Task.id)
            for task in query.all():
                icon = '\U0001F195'
                if task.status == 'DOING':
                    icon = '\U000023FA'
                elif task.status == 'DONE':
                    icon = '\U00002611'
                a += '[[{}]] {} {} - {}\n'.format(task.id, icon, task.name,
                                                  task.duedate)
                a += self.deps_text(task, chat)
            self.u.send_message(a, chat)
            a = ''
            a += '\U0001F4DD _Status_\n'
            query = db.session.query(Task).filter_by(
                status='TODO', chat=chat).order_by(Task.id)
            a += '\n\U0001F195 *TODO*\n'

            for task in query.all():
                print(task.name)
                a += '[[{}]] {} - {}\n'.format(task.id, task.name,
                                               task.duedate)
            query = db.session.query(Task).filter_by(priority='high',
                                                     chat=chat).order_by(
                                                         Task.id)
            a += '\U0001F6F0 *HIGH*\n'
            for task in query.all():
                a += '[[{}]] {} - {}\n'.format(task.id, task.name,
                                               task.duedate)
            query = db.session.query(Task).filter_by(priority='medium',
                                                     chat=chat).order_by(
                                                         Task.id)
            a += '\U0001F6F0 *MEDIUM*\n'
            for task in query.all():
                a += '[[{}]] {} - {}\n'.format(task.id, task.name,
                                               task.duedate)
            query = db.session.query(Task).filter_by(
                priority='low', chat=chat).order_by(Task.id)
            a += '\U0001F6F0 *LOW*\n'

            for task in query.all():
                a += '[[{}]] {} - {}\n'.format(task.id, task.name,
                                               task.duedate)
            query = db.session.query(Task).filter_by(
                status='DOING', chat=chat).order_by(Task.id)
            a += '\n\U000023FA *DOING*\n'
            for task in query.all():
                a += '[[{}]] {} - {}\n'.format(task.id, task.name,
                                               task.duedate)
            query = db.session.query(Task).filter_by(
                status='DONE', chat=chat).order_by(Task.id)
            a += '\n\U00002611 *DONE*\n'
            for task in query.all():
                a += '[[{}]] {} - {}\n'.format(task.id, task.name,
                                               task.duedate)
            self.u.send_message(a, chat)

        def existing_dependent_task(task, task_dependent):
            query = db.session.query(Task).filter_by(id=task)
            task_dependency = query.one()
            dependencies_task = task_dependency.dependencies.split(",")
            return str(task_dependent) in dependencies_task

        def dependson_assigment(msg, chat):
            text = ''
            if msg != '':
                if len(msg.split(' ', 1)) > 1:
                    text = msg.split(' ', 1)[1]
                msg = msg.split(' ', 1)[0]

            if not msg.isdigit():
                return "You must inform the task id"
            else:
                task_id = int(msg)
                query = db.session.query(Task).filter_by(id=task_id, chat=chat)
                try:
                    task = query.one()
                except sqlalchemy.orm.exc.NoResultFound:
                    return "_404_ Task {} not found x.x".format(task_id)

                if text == '':
                    for i in task.dependencies.split(',')[:-1]:
                        i = int(i)
                        q = db.session.query(Task).filter_by(id=i, chat=chat)
                        task_dependency = query.one()
                        task_dependency.parents = task_dependency.parents.replace(
                            '{},'.format(task.id), '')

                    task.dependencies = ''
                    return "Dependencies removed from task {}".format(
                        task_id, chat)
                elif existing_dependent_task(text, task_id):
                    return "Task {} already have a dependency of task {}".format(
                        text, task_id, chat)
                else:
                    for depid in text.split(' '):
                        if not depid.isdigit():
                            return "All dependencies ids must be numeric, and not {}".format(
                                depid)
                        else:
                            depid = int(depid)
                            query = db.session.query(Task).filter_by(id=depid,
                                                                     chat=chat)
                            try:
                                task_dependency = query.one()
                                task_dependency.parents += str(task.id) + ','
                            except sqlalchemy.orm.exc.NoResultFound:
                                return "_404_ Task {} not found x.x".format(
                                    depid)
                                continue

                            deplist = task.dependencies.split(',')
                            if str(depid) not in deplist:
                                task.dependencies += str(depid) + ','
                    if text == '':
                        task.priority = ''
                        self.u.send_message(
                            "_Cleared_ all priorities from task {}".format(
                                task_id), chat)
                    else:
                        if text.lower() not in ['high', 'medium', 'low']:
                            self.u.send_message(
                                "The priority *must be* one of the following: high, medium, low",
                                chat)
                        else:
                            task.priority = text.lower()
                            self.u.send_message(
                                "*Task {}* priority has priority *{}*".format(
                                    task_id, text.lower()), chat)
                db.session.commit()
                return "Task {} dependencies up to date".format(task_id)

        def priority_assigment(msg, chat):
            text = ''
            if msg != '':
                if len(msg.split(' ', 1)) > 1:
                    text = msg.split(' ', 1)[1]
                msg = msg.split(' ', 1)[0]
            if not msg.isdigit():
                self.u.send_message("You must inform the task id", chat)
            else:
                task_id = int(msg)
                query = db.session.query(Task).filter_by(id=task_id, chat=chat)
                try:
                    task = query.one()
                except sqlalchemy.orm.exc.NoResultFound:
                    self.u.send_message(
                        "_404_ Task {} not found x.x".format(task_id), chat)
                    return
                if text == '':
                    task.priority = ''
                    self.u.send_message(
                        "_Cleared_ all priorities from task {}".format(
                            task_id), chat)
                else:
                    if text.lower() not in ['high', 'medium', 'low']:
                        self.u.send_message(
                            "The priority *must be* one of the following: high, medium, low",
                            chat)
                    else:
                        task.priority = text.lower()
                        self.u.send_message(
                            "*Task {}* priority has priority *{}*".format(
                                task_id, text.lower()), chat)
                db.session.commit()

        for update in updates["result"]:
            if 'message' in update:
                message = update['message']
            elif 'edited_message' in update:
                message = update['edited_message']
            else:
                print('Can\'t process! {}'.format(update))
                return

            try:
                text = message["text"]
            except:
                message["text"] = ""

            command = message["text"].split(" ", 1)[0]
            msg = ''
            if len(message["text"].split(" ", 1)) > 1:
                msg = message["text"].split(" ", 1)[1].strip()
            chat = message["chat"]["id"]
            print(command, msg, chat)
            if command == '/new':
                new_assigment(msg, chat)
            elif command == '/rename':
                rename_assigment(msg, chat)
            elif command == '/duplicate':
                duplicate_assigment(msg, chat)
            elif command == '/delete':
                delete_assigment(msg, chat)
            elif command == '/todo':
                todo_assigment(msg, chat)
            elif command == '/doing':
                doing_assigment(msg, chat)
            elif command == '/done':
                done_assigment(msg, chat)
            elif command == '/list':
                list_assigment(msg, chat)
            elif command == '/dependson':
                dependson_assigment(msg, chat)
            elif command == '/priority':
                priority_assigment(msg, chat)
            elif command == '/start':
                self.u.send_message(
                    "Welcome! Here is a list of things you can do.", chat)
                self.u.send_message(self.str_help, chat)
            elif command == '/help':
                self.u.send_message("Here is a list of things you can do.",
                                    chat)
                self.u.send_message(self.str_help, chat)
            else:
                self.u.send_message(
                    "I'm sorry dave. I'm afraid I can't do that.", chat)
Esempio n. 30
0
 def post(self):
     return Item(
         Request(self.auth, "POST", self.header,
                 Url(self.urlBase, self.name + "/")), "post " + self.name)
Esempio n. 31
0
        l = Locations()
        provinces = l.get_provinces()
        province_ids = l.get_province_ids()

        # generate a string of provinces to prompt user with
        provinces_string = "\n"
        for province_no in provinces:
            provinces_string += str(province_no) + ": " + (
                provinces[province_no] + "\n")

        # second arg is the province number
        province_num = input("Enter a province number from:" +
                             provinces_string)

        # generate the kijiji url
        websiteObject = Url()

        websiteObject.set_product_name(product)
        websiteObject.set_province_num(province_num)
        websiteObject.set_provinces(provinces)
        websiteObject.set_province_ids(province_ids)

        website = websiteObject.generate()

        # webscrape the product from the website
        cheapest_product = cheapest(website, product)

        # get the info
        product_name = cheapest_product.get_name()
        product_price = cheapest_product.get_price()
        product_url = cheapest_product.get_url()
Esempio n. 32
0
 def put(self):
     return Item(
         Request(self.auth, "PUT", self.header,
                 Url(self.urlBase, self.name + "/1")), "put " + self.name)