Ejemplo n.º 1
0
        def testPersistance(self):

#            for i in h:
#                print h

            b = Buddy()
            b.uin = '123456'

            import message
            item1 = message.messageFactory("icq", 'user', '12345', 'incoming 1', Incoming)
            self.h.append(item1)

            self.h.store(b)
            self.h = None
            del self.h

            self.h = History()
            h2 = History.restore(b)

            d = h2.dump()
            assert d.split('\n')[0] == '>> : incoming 1'

            b.uin = ''
            h3 = History.restore(b)
            d = h3.dump()
            assert len(d) == 0
 def get_buddy(self, objid):
     buddy = self._buddies.get(objid)
     if buddy is None:
         _logger.debug('Creating new buddy at .../%s', objid)
         # we don't know yet this buddy
         buddy = Buddy(self._session_bus, objid)
         buddy.connect("validity-changed", self._buddy_validity_changed_cb)
         buddy.connect("disappeared", self._buddy_disappeared_cb)
         self._buddies[objid] = buddy
     return buddy
Ejemplo n.º 3
0
def _test():
    p = load_plugins(connector = None)
    log().log(p)

    m = messageFactory("icq", 'user', '12121212', 'text', Outgoing)
    b = Buddy()
    b.uin = '12121212'

    for k in p:
        p[k].onIncomingMessage(buddy = b, message = m)
Ejemplo n.º 4
0
        def __init__(self, parentFrame, title):
            wx.Frame.__init__(self, parentFrame, -1, title,
                pos=(150, 150), size=(350, 200))
            wx.Panel(self, -1)

            message = messageFactory("icq", 'user', '12345', 'text', HistoryDirection.Incoming)

#            h = History()
            b = Buddy()
            b.name = 'user'
            b.uin = '123456'
            self.d = MessageDialog(self, -1, b, message)
            self.d.Show(True)

            wx.CallAfter(self.a)
Ejemplo n.º 5
0
    def successAddFriend(self, friend, head):
        newitem = QTreeWidgetItem()
        newitem.setSizeHint(0, QSize(self.treeWidget.width(), 55))
        friendName = friend['name']
        friendId = friend['id']
        ishide = friend['ishide']
        buddy = Buddy(friendName, str(friendId), head, ishide)
        userdic = {
            'user': newitem,
            'username': friendName,
            'userid': friendId,
            'head': head,
            'ishide': ishide
        }
        for k, v in self.temp.items():
            if k == friend['id']:
                comboxinfo = self.temp.pop(k)
                break
        cindex = self.searchgroup(comboxinfo)
        group = self.grouplist[cindex]['group']
        groupname = self.grouplist[cindex]['groupname']
        self.grouplist[cindex]['childcount'] += 1
        self.userslist.append(userdic)
        group.addChild(newitem)
        self.treeWidget.setItemWidget(newitem, 0, buddy)
        self.treeWidget.setCurrentItem(newitem)

        user = {'username': friendName, 'userid': friendId, 'ishide': 0}
        self.groupInfo[groupname].append(user)
Ejemplo n.º 6
0
 def incoming_call(self, prm):
     call = Call(self.acc, call_id=prm.callId)
     call_prm = pj.CallOpParam()
     # Ringing State
     call_prm.statusCode = pj.PJSIP_SC_RINGING
     call.answer(call_prm)
     # Set uri
     call.uri = call.getInfo().remoteUri
     iid = call.uri.split(':')[1].split('@')[0]
     if msg.askquestion('Incoming Call',
                        'Accept call from ' + iid + ' ?',
                        default=msg.YES):
         # If not exist current buddy, then create
         if iid not in self.buddy_list:
             # Initialize buddy
             bud = Buddy(self, iid)
             # Initialize configuration of buddy
             bud_cfg = pj.BuddyConfig()
             bud_cfg.uri = 'sip:' + iid + '@' + self.domain
             # Create buddy
             bud.cfg = bud_cfg
             bud.create(self.acc, bud.cfg)
             bud.subscribePresence(True)
             # Push into buddy_list
             self.buddy_list[iid] = bud
             self.update_buddy(bud)
         # If not exist current chat dialog, then create
         if iid not in self.chat_list:
             self.chat_list[iid] = Chat(self.acc, self.buddy_list[iid],
                                        self)
         # Inform the corresponding chat
         self.chat_list[iid].receive_call(call)
     else:
         call.hangup(call_prm)
Ejemplo n.º 7
0
def test():
    root = tk.Tk()

    acc = Account(None)
    bud = Buddy(None, '1002')
    bud_cfg = pj.BuddyConfig()
    bud_cfg.uri = 'sip:[email protected]'

    Chat(acc, bud, root)
    root.mainloop()
Ejemplo n.º 8
0
 def _grabCurrentUser(self):
     b = Buddy()
     b.name = self.getColumnText(self.currentItem, 1)
     b.first = self.getColumnText(self.currentItem, 2)
     b.last = self.getColumnText(self.currentItem, 3)
     b.email = self.getColumnText(self.currentItem, 4)
     b.uin = self.getColumnText(self.currentItem, 5)
     return b
Ejemplo n.º 9
0
    def creategroup(self):
        self.groupInfo = groupInfo = self.client.dealInitGroupInfo()
        for groupname in groupInfo.keys():
            hidernum = 0
            group = QTreeWidgetItem(self.treeWidget)
            groupdic = {
                'group': group,
                'groupname': groupname,
                'childcount': 0,
                'childhide': 0
            }
            icon = self.searchIcon(groupname)
            group.setIcon(0, icon)

            for friend in groupInfo[groupname]:
                child = QTreeWidgetItem()
                child.setSizeHint(0, QSize(self.treeWidget.width(), 55))
                friendName = friend['username']
                friendId = friend['userid']
                ishide = friend['ishide']
                head = self.client.dealGetHead(friendId)
                buddy = Buddy(friendName, str(friendId), head, ishide)
                userdic = {
                    'user': child,
                    'username': friendName,
                    'userid': friendId,
                    'head': head,
                    'ishide': ishide
                }
                self.userslist.append(userdic)
                if friend['ishide'] == 1:
                    hidernum += 1
                    userdic['ishide'] = 1
                group.addChild(child)
                self.treeWidget.setItemWidget(child, 0, buddy)

            childnum = group.childCount()
            lastchildnum = childnum - hidernum
            groupdic['childcount'] = childnum
            groupdic['childishide'] = hidernum
            groupname += ' ' + str(lastchildnum) + '/' + str(childnum)
            group.setText(0, groupname)
            group.setExpanded(True)
            self.grouplist.append(groupdic)
Ejemplo n.º 10
0
    def _add_buddy(self, event):
        iid = self.buddy.get()

        if iid not in self.buddy_list:
            # Initialize buddy
            bud = Buddy(self, iid)
            # Initialize configuration of buddy
            bud_cfg = pj.BuddyConfig()
            bud_cfg.uri = 'sip:' + iid + '@' + self.domain
            # Create buddy
            bud.cfg = bud_cfg
            bud.create(self.acc, bud.cfg)
            bud.subscribePresence(True)
            # Push into buddy_list
            self.buddy_list[iid] = bud
            self.update_buddy(bud)

        self.buddy.delete(0, 'end')
Ejemplo n.º 11
0
    def dealBeAdded(self, widget):
        reply = QMessageBox.question(
            self, 'Friend add Prompt',
            '%s(%s)Add you as a friend' % (widget.name, widget.id),
            QMessageBox.Yes | QMessageBox.No, QMessageBox.Yes)
        if reply == QMessageBox.No:
            self.client.dealRefuseAdded(widget.id)
        else:
            info = ['my good friend', widget.name]
            dialog = Add_Dialog(info)
            for g in self.grouplist:
                dialog.comboBox.addItem(g['groupname'])
            dialog.exec_()

            self.client.dealAcceptAdded(widget.id)
            newitem = QTreeWidgetItem()
            newitem.setSizeHint(0, QSize(self.treeWidget.width(), 55))

            head = widget.data.split('\n'.encode('utf-8'), 1)[1]
            buddy = Buddy(info[1], str(widget.id), head, 0)
            userdic = {
                'user': newitem,
                'username': info[1],
                'userid': widget.id,
                'head': head,
                'ishide': 0
            }

            cindex = self.searchgroup(info[0])
            group = self.grouplist[cindex]['group']
            self.grouplist[cindex]['childcount'] += 1
            self.userslist.append(userdic)
            group.addChild(newitem)
            self.treeWidget.setItemWidget(newitem, 0, buddy)
            self.treeWidget.setCurrentItem(newitem)

            user = {'username': info[1], 'userid': widget.id, 'ishide': 0}
            self.groupInfo[info[0]].append(user)
Ejemplo n.º 12
0
    def add(self, group, items):
        gindex = self.searchgroup(group)
        gname = self.grouplist[gindex]['groupname']
        for item in items:
            aindex = self.searchuser(item)
            ishide = self.userslist[aindex]['ishide']
            userid = self.userslist[aindex]['userid']
            username = self.userslist[aindex]['username']
            head = self.userslist[aindex]['head']
            if ishide == 1:
                self.grouplist[gindex]['childishide'] += 1
                self.grouplist[gindex]['childcount'] += 1
            else:
                self.grouplist[gindex]['childcount'] += 1
            buddy = Buddy(username, str(userid), head, ishide)

            group.addChild(item)
            self.treeWidget.setItemWidget(item, 0, buddy)
            self.treeWidget.itemWidget(item, 0).show()
            self.treeWidget.setCurrentItem(item)

            user = {'username': username, 'userid': userid, 'ishide': 0}
            self.groupInfo[gname].append(user)
Ejemplo n.º 13
0
        def load_buddies(self):
            try:
                self.buddies = []
                b = config.get('Room1', 'name')
                c = config.get('Room1', 'uri')
                x = config.getint('Room1', 'subscribed')
                d = Buddy(b, c, None)
                if x == 1:
                    d.subscribed = True
                self.buddies.append(d)

                e = config.get('Room2', 'name')
                f = config.get('Room2', 'uri')
                y = config.getint('Room2', 'subscribed')
                g = Buddy(e, f, None)
                if y == 1:
                    g.subscribed = True
                self.buddies.append(g)
            except Exception, e:
                return False
Ejemplo n.º 14
0
        try:
            self_keys = self.keys()
            if invalid_fields:
                for each_invalid_field in invalid_fields:
                    if each_invalid_field in self_keys:
                        self.pop(each_invalid_field)
        except Exception, e:
            print "\nError while processing invalid fields: ", e
            pass

    # if Add-Buddy feature is enabled:
    #   - Get all user id's of active buddies with currently logged in user.
    #   - Check if each of buddy-user-id does not exists in contributors of node object, add it.
        if GSTUDIO_BUDDY_LOGIN:
            from buddy import Buddy
            buddy_contributors = Buddy.get_buddy_userids_list_within_datetime(
                self.created_by, self.last_update or self.created_at)
            # print 'buddy_contributors : ', buddy_contributors

            if buddy_contributors:
                for each_bcontrib in buddy_contributors:
                    if each_bcontrib not in self.contributors:
                        self.contributors.append(each_bcontrib)

        super(Node, self).save(*args, **kwargs)

        # This is the save method of the node class.It is still not
        # known on which objects is this save method applicable We
        # still do not know if this save method is called for the
        # classes which extend the Node Class or for every class There
        # is a very high probability that it is called for classes
        # which extend the Node Class only The classes which we have
Ejemplo n.º 15
0
    def add_visit_count(resource_obj_or_id, current_group_id, loggedin_userid):
        from node import Node
        from gsystem import GSystem

        active_user_ids_list = [loggedin_userid]
        if GSTUDIO_BUDDY_LOGIN:
            active_user_ids_list += Buddy.get_buddy_userids_list_within_datetime(
                loggedin_userid, datetime.datetime.now())
            # removing redundancy of user ids:
            # active_user_ids_list = dict.fromkeys(active_user_ids_list).keys()

        resource_obj = Node.get_node_obj_from_id_or_obj(
            resource_obj_or_id, GSystem)
        resource_oid = resource_obj._id
        resource_type, resource_type_of = Counter._get_resource_type_tuple(
            resource_obj)

        # get resource's creator:
        resource_created_by_user_id = resource_obj.created_by
        resource_contributors_user_ids_list = resource_obj.contributors

        # contributors will not get increament in visit count increment for own resource.
        diff_user_ids_list = list(
            set(active_user_ids_list) -
            set(resource_contributors_user_ids_list))
        diff_user_ids_list_length = len(diff_user_ids_list)
        if diff_user_ids_list_length == 0:
            return

        counter_objs_cur = Counter.get_counter_objs_cur(
            diff_user_ids_list, current_group_id)

        key_str_counter_resource_type = Counter.__key_str_counter_resource_type_of(
            resource_type, resource_type_of, 'each_uc')
        key_str_counter_resource_type_visits_on_others_res = key_str_counter_resource_type \
                                                              + '["visits_on_others_res"]'
        key_str_creator_counter_resource_type_visits_gained = key_str_counter_resource_type \
                                                              + '["visits_gained"]'

        for each_uc in counter_objs_cur:
            # if each_uc['user_id'] not in resource_contributors_user_ids_list:
            visits_on_others_res = eval(
                key_str_counter_resource_type_visits_on_others_res)
            eval(key_str_counter_resource_type).update(
                {"visits_on_others_res": (visits_on_others_res + 1)})
            each_uc.save()

        # contributors will not get increament in visit count increment for own resource.
        diff_contrib_ids_list = list(
            set(resource_contributors_user_ids_list) -
            set(active_user_ids_list))
        if not diff_contrib_ids_list:
            return

        creator_counter_objs_cur = Counter.get_counter_objs_cur(
            diff_contrib_ids_list, current_group_id)

        for each_uc in creator_counter_objs_cur:
            visits_gained = eval(
                key_str_creator_counter_resource_type_visits_gained)
            eval(key_str_counter_resource_type).update(
                {"visits_gained": (visits_gained + diff_user_ids_list_length)})
            each_uc.save()
Ejemplo n.º 16
0
    def save(self, *args, **kwargs):
	if "is_changed" in kwargs:
            if not kwargs["is_changed"]:
                #print "\n ", self.name, "(", self._id, ") -- Nothing has changed !\n\n"
                return

        is_new = False

        if not "_id" in self:
            is_new = True               # It's a new document, hence yet no ID!"

            # On save, set "created_at" to current date
            self.created_at = datetime.datetime.today()

        self.last_update = datetime.datetime.today()

        # Check the fields which are not present in the class
        # structure, whether do they exists in their GSystemType's
        # "attribute_type_set"; If exists, add them to the document
        # Otherwise, throw an error -- " Illegal access: Invalid field
        # found!!! "

        try:

            invalid_struct_fields = list(set(self.structure.keys()) - set(self.keys()))
            # print '\n invalid_struct_fields: ',invalid_struct_fields
            if invalid_struct_fields:
                for each_invalid_field in invalid_struct_fields:
                    if each_invalid_field in self.structure:
                        self.structure.pop(each_invalid_field)
                        # print "=== removed from structure", each_invalid_field, ' : ',


            keys_list = self.structure.keys()
            keys_list.append('_id')
            invalid_struct_fields_list = list(set(self.keys()) - set(keys_list))
            # print '\n invalid_struct_fields_list: ',invalid_struct_fields_list
            if invalid_struct_fields_list:
                for each_invalid_field in invalid_struct_fields_list:
                    if each_invalid_field in self:
                        self.pop(each_invalid_field)
                        # print "=== removed ", each_invalid_field, ' : ',


        except Exception as e:
            print e
            pass

        invalid_fields = []

        for key, value in self.iteritems():
            if key == '_id':
                continue

            if not (key in self.structure):
                field_found = False
                for gst_id in self.member_of:
                    attribute_set_list = node_collection.one({'_id': gst_id}).attribute_type_set

                    for attribute in attribute_set_list:
                        if key == attribute['name']:
                            field_found = True

                            # TODO: Check whether type of "value"
                            # matches with that of
                            # "attribute['data_type']" Don't continue
                            # searching from list of remaining
                            # attributes
                            break

                    if field_found:
                        # Don't continue searching from list of
                        # remaining gsystem-types
                        break

                if not field_found:
                    invalid_fields.append(key)
                    print "\n Invalid field(", key, ") found!!!\n"
                    # Throw an error: " Illegal access: Invalid field
                    # found!!! "

        # print "== invalid_fields : ", invalid_fields
        try:
            self_keys = self.keys()
            if invalid_fields:
                for each_invalid_field in invalid_fields:
                    if each_invalid_field in self_keys:
                        self.pop(each_invalid_field)
        except Exception as e:
            print "\nError while processing invalid fields: ", e
            pass

        # if Add-Buddy feature is enabled:
        #   - Get all user id's of active buddies with currently logged in user.
        #   - Check if each of buddy-user-id does not exists in contributors of node object, add it.
        if GSTUDIO_BUDDY_LOGIN:
            from buddy import Buddy
            buddy_contributors = Buddy.get_buddy_userids_list_within_datetime(
                                                    self.created_by,
                                                    self.last_update or self.created_at
                                                )
            # print 'buddy_contributors : ', buddy_contributors

            if buddy_contributors:
                for each_bcontrib in buddy_contributors:
                    if each_bcontrib not in self.contributors:
                        self.contributors.append(each_bcontrib)

        super(Node, self).save(*args, **kwargs)

        # This is the save method of the node class.It is still not
        # known on which objects is this save method applicable We
        # still do not know if this save method is called for the
        # classes which extend the Node Class or for every class There
        # is a very high probability that it is called for classes
        # which extend the Node Class only The classes which we have
        # i.e. the MyReduce() and ToReduce() class do not extend from
        # the node class Hence calling the save method on those objects
        # should not create a recursive function

        # If it is a new document then Make a new object of ToReduce
        # class and the id of this document to that object else Check
        # whether there is already an object of ToReduce() with the id
        # of this object.  If there is an object present pass else add
        # that object I have not applied the above algorithm

        # TO BE COMMENTED map-reduce code:
        # 
        # Instead what I have done is that I have searched the
        # ToReduce() collection class and searched whether the ID of
        # this document is present or not.  If the id is not present
        # then add that id.If it is present then do not add that id

        old_doc = node_collection.collection.ToReduceDocs.find_one({'required_for':to_reduce_doc_requirement,'doc_id':self._id})

        #print "~~~~~~~~~~~~~~~~~~~~It is not present in the ToReduce() class collection.Message Coming from save() method ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~",self._id
        if  not old_doc:
            z = node_collection.collection.ToReduceDocs()
            z.doc_id = self._id
            z.required_for = to_reduce_doc_requirement
            z.save()

        #If you create/edit anything then this code shall add it in the URL

        history_manager = HistoryManager()
        rcs_obj = RCS()

        if is_new:
            # Create history-version-file
            try:
                if history_manager.create_or_replace_json_file(self):
                    fp = history_manager.get_file_path(self)
                    user_list = User.objects.filter(pk=self.created_by)
                    user = user_list[0].username if user_list else 'user'
                    # user = User.objects.get(pk=self.created_by).username
                    message = "This document (" + self.name + ") is created by " + user + " on " + self.created_at.strftime("%d %B %Y")
                    rcs_obj.checkin(fp, 1, message.encode('utf-8'), "-i")
            except Exception as err:
                print "\n DocumentError: This document (", self._id, ":", self.name, ") can't be created!!!\n"
                node_collection.collection.remove({'_id': self._id})
                raise RuntimeError(err)

        else:
            # Update history-version-file
            fp = history_manager.get_file_path(self)

            try:
                rcs_obj.checkout(fp, otherflags="-f")
            except Exception as err:
                try:
                    if history_manager.create_or_replace_json_file(self):
                        fp = history_manager.get_file_path(self)
                        # user = User.objects.get(pk=self.created_by).username
                        user_list = User.objects.filter(pk=self.created_by)
                        user = user_list[0].username if user_list else 'user'
                        message = "This document (" + self.name + ") is re-created by " + user + " on " + self.created_at.strftime("%d %B %Y")
                        rcs_obj.checkin(fp, 1, message.encode('utf-8'), "-i")

                except Exception as err:
                    print "\n DocumentError: This document (", self._id, ":", self.name, ") can't be re-created!!!\n"
                    node_collection.collection.remove({'_id': self._id})
                    raise RuntimeError(err)

            try:
                if history_manager.create_or_replace_json_file(self):
                    # user = User.objects.get(pk=self.modified_by).username
                    user_list = User.objects.filter(pk=self.created_by)
                    user = user_list[0].username if user_list else 'user'
                    message = "This document (" + self.name + ") is lastly updated by " + user + " status:" + self.status + " on " + self.last_update.strftime("%d %B %Y")
                    rcs_obj.checkin(fp, 1, message.encode('utf-8'))

            except Exception as err:
                print "\n DocumentError: This document (", self._id, ":", self.name, ") can't be updated!!!\n"
                raise RuntimeError(err)

        #update the snapshot feild
        if kwargs.get('groupid'):
            # gets the last version no.
            rcsno = history_manager.get_current_version(self)
            node_collection.collection.update({'_id':self._id}, {'$set': {'snapshot'+"."+str(kwargs['groupid']):rcsno }}, upsert=False, multi=True)
Ejemplo n.º 17
0
    def save(self, *args, **kwargs):
        if "is_changed" in kwargs:
            if not kwargs["is_changed"]:
                #print "\n ", self.name, "(", self._id, ") -- Nothing has changed !\n\n"
                return

        is_new = False

        if not "_id" in self:
            is_new = True  # It's a new document, hence yet no ID!"

            # On save, set "created_at" to current date
            self.created_at = datetime.datetime.today()

        self.last_update = datetime.datetime.today()

        # Check the fields which are not present in the class
        # structure, whether do they exists in their GSystemType's
        # "attribute_type_set"; If exists, add them to the document
        # Otherwise, throw an error -- " Illegal access: Invalid field
        # found!!! "

        try:

            invalid_struct_fields = list(
                set(self.structure.keys()) - set(self.keys()))
            # print '\n invalid_struct_fields: ',invalid_struct_fields
            if invalid_struct_fields:
                for each_invalid_field in invalid_struct_fields:
                    if each_invalid_field in self.structure:
                        self.structure.pop(each_invalid_field)
                        # print "=== removed from structure", each_invalid_field, ' : ',

            keys_list = self.structure.keys()
            keys_list.append('_id')
            invalid_struct_fields_list = list(
                set(self.keys()) - set(keys_list))
            # print '\n invalid_struct_fields_list: ',invalid_struct_fields_list
            if invalid_struct_fields_list:
                for each_invalid_field in invalid_struct_fields_list:
                    if each_invalid_field in self:
                        self.pop(each_invalid_field)
                        # print "=== removed ", each_invalid_field, ' : ',

        except Exception as e:
            print e
            pass

        invalid_fields = []

        for key, value in self.iteritems():
            if key == '_id':
                continue

            if not (key in self.structure):
                field_found = False
                for gst_id in self.member_of:
                    attribute_set_list = node_collection.one({
                        '_id': gst_id
                    }).attribute_type_set

                    for attribute in attribute_set_list:
                        if key == attribute['name']:
                            field_found = True

                            # TODO: Check whether type of "value"
                            # matches with that of
                            # "attribute['data_type']" Don't continue
                            # searching from list of remaining
                            # attributes
                            break

                    if field_found:
                        # Don't continue searching from list of
                        # remaining gsystem-types
                        break

                if not field_found:
                    invalid_fields.append(key)
                    print "\n Invalid field(", key, ") found!!!\n"
                    # Throw an error: " Illegal access: Invalid field
                    # found!!! "

    # print "== invalid_fields : ", invalid_fields
        try:
            self_keys = self.keys()
            if invalid_fields:
                for each_invalid_field in invalid_fields:
                    if each_invalid_field in self_keys:
                        self.pop(each_invalid_field)
        except Exception as e:
            print "\nError while processing invalid fields: ", e
            pass

    # if Add-Buddy feature is enabled:
    #   - Get all user id's of active buddies with currently logged in user.
    #   - Check if each of buddy-user-id does not exists in contributors of node object, add it.
        if GSTUDIO_BUDDY_LOGIN:
            from buddy import Buddy
            buddy_contributors = Buddy.get_buddy_userids_list_within_datetime(
                self.created_by, self.last_update or self.created_at)
            # print 'buddy_contributors : ', buddy_contributors

            if buddy_contributors:
                for each_bcontrib in buddy_contributors:
                    if each_bcontrib not in self.contributors:
                        self.contributors.append(each_bcontrib)

        super(Node, self).save(*args, **kwargs)

        # This is the save method of the node class.It is still not
        # known on which objects is this save method applicable We
        # still do not know if this save method is called for the
        # classes which extend the Node Class or for every class There
        # is a very high probability that it is called for classes
        # which extend the Node Class only The classes which we have
        # i.e. the MyReduce() and ToReduce() class do not extend from
        # the node class Hence calling the save method on those objects
        # should not create a recursive function

        # If it is a new document then Make a new object of ToReduce
        # class and the id of this document to that object else Check
        # whether there is already an object of ToReduce() with the id
        # of this object.  If there is an object present pass else add
        # that object I have not applied the above algorithm

        # TO BE COMMENTED map-reduce code:
        #
        # Instead what I have done is that I have searched the
        # ToReduce() collection class and searched whether the ID of
        # this document is present or not.  If the id is not present
        # then add that id.If it is present then do not add that id

        old_doc = node_collection.collection.ToReduceDocs.find_one({
            'required_for':
            to_reduce_doc_requirement,
            'doc_id':
            self._id
        })

        #print "~~~~~~~~~~~~~~~~~~~~It is not present in the ToReduce() class collection.Message Coming from save() method ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~",self._id
        if not old_doc:
            z = node_collection.collection.ToReduceDocs()
            z.doc_id = self._id
            z.required_for = to_reduce_doc_requirement
            z.save()

    #If you create/edit anything then this code shall add it in the URL

        history_manager = HistoryManager()
        rcs_obj = RCS()

        if is_new:
            # Create history-version-file
            try:
                if history_manager.create_or_replace_json_file(self):
                    fp = history_manager.get_file_path(self)
                    user_list = User.objects.filter(pk=self.created_by)
                    user = user_list[0].username if user_list else 'user'
                    # user = User.objects.get(pk=self.created_by).username
                    message = "This document (" + self.name + ") is created by " + user + " on " + self.created_at.strftime(
                        "%d %B %Y")
                    rcs_obj.checkin(fp, 1, message.encode('utf-8'), "-i")
            except Exception as err:
                print "\n DocumentError: This document (", self._id, ":", self.name, ") can't be created!!!\n"
                node_collection.collection.remove({'_id': self._id})
                raise RuntimeError(err)

        else:
            # Update history-version-file
            fp = history_manager.get_file_path(self)

            try:
                rcs_obj.checkout(fp, otherflags="-f")
            except Exception as err:
                try:
                    if history_manager.create_or_replace_json_file(self):
                        fp = history_manager.get_file_path(self)
                        # user = User.objects.get(pk=self.created_by).username
                        user_list = User.objects.filter(pk=self.created_by)
                        user = user_list[0].username if user_list else 'user'
                        message = "This document (" + self.name + ") is re-created by " + user + " on " + self.created_at.strftime(
                            "%d %B %Y")
                        rcs_obj.checkin(fp, 1, message.encode('utf-8'), "-i")

                except Exception as err:
                    print "\n DocumentError: This document (", self._id, ":", self.name, ") can't be re-created!!!\n"
                    node_collection.collection.remove({'_id': self._id})
                    raise RuntimeError(err)

            try:
                if history_manager.create_or_replace_json_file(self):
                    # user = User.objects.get(pk=self.modified_by).username
                    user_list = User.objects.filter(pk=self.created_by)
                    user = user_list[0].username if user_list else 'user'
                    message = "This document (" + self.name + ") is lastly updated by " + user + " status:" + self.status + " on " + self.last_update.strftime(
                        "%d %B %Y")
                    rcs_obj.checkin(fp, 1, message.encode('utf-8'))

            except Exception as err:
                print "\n DocumentError: This document (", self._id, ":", self.name, ") can't be updated!!!\n"
                raise RuntimeError(err)

    #update the snapshot feild
        if kwargs.get('groupid'):
            # gets the last version no.
            rcsno = history_manager.get_current_version(self)
            node_collection.collection.update(
                {'_id': self._id},
                {'$set': {
                    'snapshot' + "." + str(kwargs['groupid']): rcsno
                }},
                upsert=False,
                multi=True)
Ejemplo n.º 18
0
    def save(self, fileName = None):
        if fileName is None:
            fileName = self._fileName
        dump2file(fileName, self)

    @staticmethod
    def load(fileName):
        return restoreFromFile(fileName)


if __name__ == '__main__':
    g = Group('groups.dump')
    g.add(1, '#1')
    g.add(2, '#2')

    b1 = Buddy()
    b1.name = 'b1'

    b2 = Buddy()
    b2.name = 'b2'

    b3 = Buddy()
    b3.name = 'b3'

    g.addBuddy(1, b1)
    g.addBuddy(2, b2)
    g.addBuddy(2, b3)
    print g

    print g.getBuddies()
    print g.getBuddies(1)