Example #1
0
    def load_work_state(self, event=None):

        message = 'Any unsaved work that you have open will be lost. Continue?'
        load_work = tkMessageBox.askyesno('Load work state?', message)

        if load_work:
            work_state_file = tkFileDialog.askopenfilename()
            if work_state_file:
                self.work_state_filename = work_state_file
                work_state = cPickle.load(open(self.work_state_filename, 'r'))
                self.root_notice_file = work_state['root_notice']
                self.notices_files = work_state['open_notices']
                self.terms = work_state['definitions']
                self.always_fix = work_state['always_fix']
                self.never_fix = work_state['never_fix']

                self.root_notice = Notice(self.root_notice_file)
                self.current_notice = self.root_notice.document_number
                self.add_element_to_tree(self.root_notice.tree, None)
                self.trees[self.root_notice.document_number] = self.root_notice
                self.populate_definitions()
                self.notices.append(self.root_notice.document_number)

                notices = [
                    Notice(notice_file) for notice_file in self.notices_files
                ]
                notices.sort(key=lambda n: n.effective_date)

                for notice in notices:
                    self.notices.append(notice.document_number)
                    self.trees[notice.document_number] = notice

                self.update_notices_list()
                self.populate_definitions()
Example #2
0
 def initialize_notice(self):
     log_file = self.conf.get("log", None)
     if log_file is not None:
         log_notice = OutputToFile(log_file)
         self.notice = Notice(log_notice, log_notice)
     else:
         self.notice = Notice()
Example #3
0
    def open_root_notice(self):

        load_root = False

        if self.root_notice is not None:
            message = "You already have a root notice loaded. If you load " + \
            "another root notice, your current set of notices will be replaced. " + \
            "Are you sure you want to do this?"
            result = tkMessageBox.askokcancel('Replace root?', message)
            if result:
                load_root = True
        else:
            load_root = True

        if load_root:
            self.notices = []
            self.root_notice = None
            self.current_notice = None
            self.trees = {}
            for child in self.element_tree.get_children():
                self.element_tree.delete(child)

            notice_file = tkFileDialog.askopenfilename()
            if notice_file:
                notice = Notice(notice_file)
                self.current_notice = notice.document_number
                self.notices.append(notice.document_number)
                self.root_notice = notice
                self.root_notice_file = notice_file
                self.add_element_to_tree(notice.tree, None)
                self.update_notices_list()
                self.trees[notice.document_number] = self.root_notice
                self.populate_definitions()

                cfr_section = notice.tree.find('{eregs}preamble').find(
                    './/{eregs}section').text
                all_notice_files = find_all(cfr_section, is_notice=True)

                message = "There are {} additional notices associated with this root version. ".format(len(all_notice_files)) + \
                    "Would you like to load all of them? This can take some time if the notices " + \
                    "are very large."
                result = tkMessageBox.askokcancel('Load all notices?', message)
                if result:
                    self.notices_files = all_notice_files
                    all_notices = [
                        Notice(notice_file) for notice_file in all_notice_files
                    ]
                    all_notices.sort(key=lambda n: n.effective_date)
                    for notice in all_notices:
                        self.notices.append(notice.document_number)
                        self.trees[notice.document_number] = notice

                    self.update_notices_list()
                    self.populate_definitions()
Example #4
0
def insert(root=None):
    logging.debug("called : %s", __name__)
    logging.debug("argument root : %s", root)

    if root is None:
        logging.debug("empty root is received")
        root = os.path.abspath(os.path.dirname(__file__)) + "/gen/json"
    if not os.path.isdir(root):
        logging.debug("making directory : %s", root)
        os.makedirs(root)

    notices = extract.get_notice_list(False)
    if notices is None:
        logging.error("error getting notice list")
        return None
    count = 0
    for notice in notices:
        timestamp = str(notice['timestamp'])
        path = root + '/' + timestamp + '.json'
        if os.path.isfile(path):
            continue
        else:
            count += 1
            print "Saved notice dated '{}' titled '{}'.".format(
                notice['time'], notice['title'])
            logging.info("Saved notice dated %s titled %s", notice['time'],
                         notice['title'])

            n = Notice(timestamp)
            n.save_json(notice)

    logging.info("%d notices inserted", count)
    return count
Example #5
0
def send_name(filename):
    '''Send the notification for the notice of given json filename'''
    logging.debug("called : %s", __name__)
    logging.debug("argument filename : %s", filename)

    if filename is None:
        logging.error("empty filename received")
        return

    n = Notice(filename)
    notice = n.get_json()

    # If the notice is not updated, update it.
    logging.debug("checking if notice is updated")
    if not notice['updated']:
        update.update_json(filename)
        notice = n.get_json()

    # If the notice is not sent, send it.
    logging.debug("checking if notice is sent")
    if not notice['sent']:
        if send_json(notice):
            # If notice is sent, save it locally. So that it is not
            # sent again.
            logging.debug("notice is sent - saving it locally")
            notice['sent'] = True
            n.save_json(notice)
            return True
        else:
            logging.error("failed sending notice")
            return False
    else:
        logging.debug("notice is already sent")
        return False
Example #6
0
def get_text_path(path):
    """
	Given path to json file, return a formatted body string with all the details
	"""
    logging.debug("called : %s", __name__)
    logging.debug("argument path : ", path)
    n = Notice(path)
    notice = n.get_json()
    return get_text_dict(notice)
Example #7
0
 def get_notice(self, content, notice_type):
     class_name = notice_type.capitalize()
     notices = content.find(id=notice_type)
     if notices and len(notices):
         notices = notices.find(class_="list-block").children
         for notice in notices:
             if notice != '\n':
                 description, link, date = self.parse_content(notice)
                 new_notice = Notice(notice_type, description, link, date)
                 new_notice.save_notice()
 def get(self, uid=None):
     """
     获取通知,传入 uid: str 来指定获取用于指定用户的通知,缺省 uid=None 获取所有通知
     """
     notices = []
     for r in self.collection.find() or []:
         n = Notice().from_dict(r)
         if n.is_expired():
             self.drop_expired(n)
         if uid == None or n.is_for_user(uid):
             notices.append(n.dumps())
     return notices
def sent_false():
	logging.debug('called : sent_false')
	root = os.path.abspath(os.path.dirname(__file__))
	path = root + '/gen/json/'
	listfile = os.listdir(path)
	if 'old' in listfile:
		listfile.remove('old')
	for fl in listfile:
		n = Notice(fl)
		notice = n.get_json()
		if not notice['sent']:
			notice['sent'] = True
			n.save_json(notice)
    def drop_expired(self, notice=None):
        """
        调用 `nu.drop_expired()` 将清除数据库中所有过期的通知

        调用 `nu.drop_expired(notice)` 将删除数据库中 nid = notice.nid 的一条通知,(这是用来支持 `nu.drop_expired()` 的工作的,也可以用来删除通知,但不推荐使用)
        """
        if isinstance(notice, Notice):
            self.collection.delete_one({"nid": notice.nid})
        else:
            for r in self.collection.find() or []:
                n = Notice().from_dict(r)
                if n.is_expired():
                    self.drop_expired(n)
Example #11
0
    def open_additional_notice(self):

        notice_file = tkFileDialog.askopenfilename()

        if notice_file:
            replace_notice = True
            notice = Notice(notice_file)
            if notice.document_number in self.notices:
                message = 'You already have this notice loaded. If you reload it, ' + \
                    'your unsaved work will be replaced. Are you sure you want to do this?'
                replace_notice = tkMessageBox.askokcancel(
                    'Replace notice?', message)

            if replace_notice:
                self.notices.append(notice.document_number)
                self.notices_files.append(notice_file)
                self.trees[notice.document_number] = notice
                self.update_notices_list()
                self.populate_definitions()
Example #12
0
def update_json(name):
    logging.debug("called : %s", __name__)
    logging.debug("argument name : %s", name)

    path = jsondir + name
    if not os.path.isfile(path):
        logging.error("json file '%s' is not present.", path)
        return

    n = Notice(name)
    notice = n.get_json()

    # If the json is erroneous, i.e, has empty fields like topic etc, start
    # fresh by removing the json file. This way the json will be reloaded at
    # next cron update.
    if erroneous_json(notice):
        logging.error("Encountered errnoneous json %s. Deleting.", str(path))
        os.remove(path)
        return False

    # If notice is updated, do not update it once more.
    if notice['updated']:
        logging.info("notice %s is already updated", name)
        return False

    details = get_details_url(notice['url'], notice['num_attachments'] == 1)

    logging.debug(
        "Notice has been updated with information from the notice	page")
    notice['updated'] = True
    notice['text'] = details['text']
    if notice['num_attachments'] == 1:
        notice['attachments'] = details['attachments']
        notice['num_attachments'] = len(details['attachments'])

    logging.debug('Saving the updated notice')
    n.save_json(notice)

    return True
Example #13
0
bot1 = Bot(console_qr=True, cache_path=True)

@bot1.register()
def print_others(msg):
    print (msg)
    if msg.is_at:
        txt = msg.text + ""
        return auto_reply(txt.replace(u"@小鸡", ""))


# 调用青人客机器人API,发送消息并获得机器人的回复
def auto_reply(text):
    result = json.loads(
                requests.get("http://api.qingyunke.com/api.php?key=free&appid=0&msg=" + text).content
            )
    return result["content"].replace("{br}", "\r\n")

print bot1.groups()

sz_track = bot1.groups().search(u'招赢通Test Track')[0]
# sz_track = bot1.groups().search(u'123456')[0]
# groups = [sz_track]
groups = bot1.groups().search(u'123456')
print groups

if __name__ == "__main__":
    CmbTracker(groups).start()
    Notice(groups).start();
    embed()
Example #14
0
 def notice_dal(self):
     return Notice()
Example #15
0
 def __init__(self, core=None, notice=None):
     self.core = core if core is not None else Core()
     self.info = notice if notice is not None else Notice()
Example #16
0
    def notice_dal(self): return Notice()

    @property
Example #17
0
# 可以把需要的群组加入到groups当中
groups = [sz_track]

plugIns = []


def start():
    for plugIn in plugIns:
        plugIn.start()


# 监控并分发消息
def monitor(msg):
    for plugIn in plugIns:
        try:
            if hasattr(plugIn, "monitor"):
                if re.search(plugIn.reg, msg, re.I) != None:
                    plugIn.monitor(msg)
                    return True
        except AttributeError as e:
            pass
    return False


if __name__ == "__main__":
    # 新开发的组件,继续往该数组当中加,
    # 新组件的启动函数统一为start
    # 新组件的监控函数统一为monitor,组件匹配消息的正则表达式为reg,该方法参数为msg文本
    plugIns.extend([CmbTracker(groups), Notice(groups)])
    start()
    embed()
Example #18
0
    for plugIn in plugIns:
        plugIn.start()


# 监控并分发消息
def monitor(msg):
    for plugIn in plugIns:
        try:
            if hasattr(plugIn, "monitor"):
                if re.search(plugIn.reg, msg.text, re.I) != None:
                    plugIn.monitor(msg)
                    return True
        except AttributeError as e:
            pass
    return False


if __name__ == "__main__":
    # 新开发的组件,继续往该数组当中加,
    # 新组件的启动函数统一为start
    # 新组件的监控函数统一为monitor,组件匹配消息的正则表达式为reg,该方法参数为msg文本
    plugIns.extend([
        CmbTracker(groups),
        Notice(groups),
        Session(groups),
        StoryAttachment(),
        CITracker(groups)
    ])
    start()
    embed()