def was_updated(): ''' Show the release notes (if any) after an update. (the updater starts the app with --updated after it completes) ''' if not sys.opts.updated: return p = common.profile() # TODO: create some sort of dummy buddy object, this is silly buddy = util.Storage(name="digsby.org", service="digsby", protocol=p.connection, increase_log_size=lambda *a, **k: None, icon=None) # make message object, release_notes = _get_release_notes() if not release_notes.strip(): return msg = common.message.Message(buddy=buddy, message=release_notes, content_type="text/html", conversation=util.Storage( protocol=p.connection, buddy=buddy, ischat=False)) p.on_message(msg)
def from_json(self, js): if isinstance(js, MyspaceComment): return js return MyspaceComment( util.Storage(author=util.Storage(id=js.get('userid')), body=js['text'], commentId=js['commentId'], postedDate=js.get('postedDate', None), postedDate_parsed=js.get('postedDate_parsed', None)))
def post_comment(self, post_id, comment, callback=None): # TODO: post comment. post = self.get_post_by_id(post_id) comment_data = util.Storage({ 'author': util.Storage({'id': self.userid}), 'body': comment }) params = { 'format': 'json', 'fields': 'author,displayName,profileUrl,thumbnailUrl' } statusId = getattr(post, 'statusId', None) if statusId is not None: params['statusId'] = statusId else: params['postedDate'] = post.published def error(e): if e.code == 401: opensocial_err = getattr(e, 'headers', {}).get('x-opensocial-error', None) log.info("got opensocial_err = %r", opensocial_err) if opensocial_err is None: return callback.error(error_obj=e) elif opensocial_err == 'Application does not have permission to publish activities.': return callback.error(error_msg=opensocial_err, permissions=True) else: return callback.error(error_msg=opensocial_err) elif e.code == 404: return callback.error(error_msg=_( "Activity stream item not found. It may have been removed by its creator." )) else: return callback.error(error_obj=e) self.api.call('statusmoodcomments/%s/@self/%s' % (post.author_id, post.id), OpenSocial=True).POST( data=json.dumps(dict(comment_data)), parameters=params, use_default_params=False, success=lambda *a: self._check_post_comment_success( post_id, comment_data, callback, *a), error=error)
def icq_cli_07d0_03f3(o): ''' LNTS xx xx ... CITY The work city. LNTS xx xx ... STATE The work state. LNTS xx xx ... PHONE The work phone number. LNTS xx xx ... FAX The FAX number as a string. LNTS xx xx ... STREET The work street address. LNTS xx xx ... ZIP The work ZIP code. WORD.L xx xx COUNTRY The work country code. LNTS xx xx ... COMPANY The work company's name. LNTS xx xx ... DEPART The work department. LNTS xx xx ... POSITION The work position. (directly after DEPART) LNTS xx xx ... ZIP The work ZIP code (huh, again?). WORD.L xx xx OCCUPATION The work occupation. LNTS xx xx ... HOMEPAGE the work home page. ''' work = getattr(o.self_buddy, 'work',util.Storage()) data = [struct.pack('<H', 0x03f3)] for attr in 'city state phone fax street zip'.split(): data.append(lnts(getattr(work, attr, ''))) data.append(struct.pack('<H', getattr(work, 'country', 0))) for attr in 'company department position zip'.split(): data.append(lnts(getattr(work, attr, ''))) data.append(struct.pack('<H', getattr(work, 'occupation', 0))) data.append(lnts(getattr(work, 'website', ''))) return icq_cli_07d0(o, ''.join(data))
def icq_cli_07d0_03fd(o): ''' WORD.L xx xx AGE Your age. BYTE xx GENDER Your gender. LNTS xx xx ... HOMEPAGE Your personal home page. WORD.L xx xx YEAR Your year of birth. BYTE xx MONTH Your month of birth. BYTE xx DAY Your day of birth. BYTE xx LANG1 Your first language. BYTE xx LANG2 Another language you speak. BYTE xx LANG3 Another language you speak. ''' info = getattr(o.self_buddy, 'personal ',util.Storage()) data = [struct.pack('<H', 0x03fd)] data.append(struct.pack('<H', getattr(info, 'age', 0))) data.append(struct.pack('<B', getattr(info, 'gender', 0))) data.append(lnts(getattr(info, 'website', 0))) data.append(struct.pack('<H', getattr(info, 'birthyear', 0))) for attr in 'month day lang1 lang2 lang3'.split(): data.append(lnts(getattr(info, attr, 0))) return icq_cli_07d0(o, ''.join(data))
def icq_srv_07da_00d2(o, uid, result, data): fmt = ''' city lnts state lnts phone lnts fax lnts street lnts zip lnts country H company lnts department lnts position lnts occupation H website lnts zip lnts '''.split() names, types = fmt[::2],fmt[1::2] fmt = zip(names, types) values, data = unpack_decode(fmt, data, '<') info = dict(zip(names, values)) info['country'] = icq_country.codes[info['country']] b = o.buddies[uid] try: work = b.work except Exception: work = b.work = util.Storage() for x in names: setattr(work, x, info[x])
def on_growl_data(data): gmsg = e = None for password in common.pref("gntp.password_list", type=list, default=[]) + [None]: try: gmsg = gntp.parse_gntp(data, password) except gntp.BaseError as e: continue else: e = None break else: if e is not None: raise e headers = {} for key, value in gmsg.headers.items(): # value_chunks = email.Header.decode_header(value) # value = ''.join(chunk.decode(charset) for (chunk, charset) in value_chunks) headers[key.lower()] = value.decode('utf8') on_growl_message( util.Storage(info=gmsg.info, headers=headers, resources=gmsg.resources)) return str(gntp.GNTPOK(action=gmsg.info['messagetype']))
def OnData(self, x, y, d): if not self.GetData(): return dragged = self.dragged dropped = util.Storage(files=dragged.file.GetFilenames(), bitmap=dragged.bitmap.GetBitmap(), text=dragged.text.GetText(), blist_item=dragged.blist_item.GetData()) import contacts.contactsdnd as contactsdnd #print 'format count', dragged.GetFormatCount() #print 'is supported', dragged.IsSupported(contactsdnd.dataformat()) #print 'BLIST_ITEM', repr(dropped.blist_item) if dropped.files: self.imwin.Top.Raise() contactdialogs.send_files(self.imwin, self.imwin.convo.buddy, dropped.files) return True if dropped.bitmap: return True if dropped.text: self.imwin.input_area.SetValue(dropped.text) self.imwin.input_area.tc.SetSelection(-1, -1) return True return False
def __init__(self, name, protocol): self._status = 'unknown' self._idle_time = None self._friendly_name = None # will be set by OscarContact self._avail_msg = self._away_msg = None self._user_class = \ self.create_time = \ self.signon_time = 0 common.buddy.__init__(self, oscar._lowerstrip(name), protocol) if isinstance(self.name, unicode): self.name = self.name.encode('utf8') self.account_creation_time = \ self.online_time = None self.user_status_icq = 'offline' self.external_ip_icq = 0 self._dc_info = util.Storage() self._capabilities = [] self.userinfo = {} if self._profile is False: self._profile = None self._away_updated = self._mystery_updated = 0 self._waiting_for_presence = True
def unpack_extended_data(data): 'Unpacks the capabilities/extra data (TLV 0x2711) in a rendezvous packet.' multiple, filecount, totalbytes = struct.unpack('!HHI', data[:8]) data = data[8:] filename, data = read_cstring(data) return util.Storage( numfiles = filecount, multiple = multiple == 0x002, size = totalbytes, name = filename ), data
def setup(self): FT.FileTransfer.__init__(self) self.name = _("Digsby Update") self.buddy = util.Storage(name = "Digsby Servers", alias = "Digsby Servers", icon = None) self.xfer_display_strings[self.states.CHECKING_FILES] = \ self.xfer_display_strings[self.states.TRANSFERRING] = \ lambda x, d=None: _('%s: %s of %s -- %s remain') % (x.state, x.completed, x.size, util.nicetimecount(x.ETA)) log.info("UpdateProgress setup")
def del_comment(self, comment_id, id, post_id): t = FBIB(self) context = util.Storage() context['post'] = self.connection.last_stream['post_ids'][post_id] comment_link_html = t.get_html(None, set_dirty=False, file='comment_link.py.xml', dir=t.get_context()['app'].get_res_dir('base'), context=context) comment_post_link = t.get_html(None, set_dirty=False, file='comment_post_link.py.xml', dir=t.get_context()['app'].get_res_dir('base'), context=context) self.Dsuccess(id, comment_id=comment_id, comment_link_html=comment_link_html, comment_post_link=comment_post_link)
def icq_srv_07da_0106(o, uid, result, data): fmt = [(x, 'lnts') for x in 'nick first last email'.split()] nick, first, last, email, data = oscar.unpack(fmt, data, '<') b = o.buddies[uid] try: b.personal except Exception: b.personal = util.Storage() set = lambda k,v: (b.setnotifyif(k,v), setattr(b.personal, k,v)) set('nick', nick) set('first', first) set('last', last) set('email', email)
def _check_post_comment_success(self, post_id, comment_data, callback, result): log.info('Got post comment result: %r', result) post = self.get_post_by_id(post_id) comment_collection = post.comments now = int(time.time()) comment = objects.MyspaceComment( util.Storage( commentId="fake-comment-id-%r" % now, postedDate_parsed=now, body=comment_data.body, author=comment_data.author, )) post.comments.append(comment) post.commentsRetrievedDate = 0 hooks.notify('digsby.myspace.comment_added', comment_data) callback.success()
def update_item_to_notification(self, item): import weakref import gui.browser.webkit.imageloader as imageloader default_icon = skin.get('BuddiesPanel.BuddyIcons.NoIcon', None) if hasattr(item, 'content_body'): body = item.content_body() else: html = self.generate_item_html(item) body = util.strip_html(html).strip() n = util.Storage(acct=weakref.ref(self), icon=imageloader.LazyWebKitImage( item.person.picture_url, default_icon), body=body, title=item.person.name, url=getattr(item, 'url', item.person.profile_url), post_id=item.id) return n
def icq_srv_07da_00c8(o, uid, result, data): if result != SUCCESS: log.warning('icq got response %d', result) return vals = 'nick first last email city state phone fax street cellular zip country timezone publish webaware data'.split() fmt = [(x, 'lnts') for x in vals[:11]] fmt.extend([ (vals[11], 'H'), (vals[12], 'B'), (vals[13], 'H'), (vals[14], 'B') ]) #locals.update(zip(vals, oscar.unpack(fmt, data, '<'))) (nick, first, last, email, city, state, phone, fax, street, cellular, zip, country_code, timezone, publish, webaware), data = unpack_decode(fmt, data, '<') country = icq_country.codes.get(country_code, sentinel) if country is sentinel: log.warning('Unknown country code %r. Maybe you can guess from these locals? %r', country_code, locals()) country = u'Unknown' del country_code if data: log.warning('icq user info got extra data: %r', util.to_hex(data)) webaware = bool(webaware%2) b = o.buddies[str(uid)] try: personal = b.personal except Exception: personal = b.personal = util.Storage() set = b.setnotifyif for x in vals: set(x, locals()[x]) setattr(personal, x, locals()[x])
def construct_advanced_subpanel_social(panel, SP, MSP, MSC): freq_defaults = dict((k, MSC.info.defaults.get(k, 2)) for k in [ 'friends_timeline', 'replies', 'direct_messages', 'search_updatefreq' ]) freq_settings = dict((k, getattr(SP, k, freq_defaults[k])) for k in [ 'friends_timeline', 'replies', 'direct_messages', 'search_updatefreq' ]) fake_account = util.Storage( update_frequencies=freq_settings, auto_throttle=getattr(SP, 'auto_throttle', MSC.info.defaults.get('auto_throttle', True)), api_server=getattr(SP, 'api_server', MSC.info.defaults.get('api_server', u'')), ) twap = twitter_account_gui.TwitterAccountPanel(panel, fake_account) panel.controls.update(twitterpanel=twap) fx = panel.controls['advanced_sz'] fx.Add(twap, (fx.row, 1), (1, 4), wx.EXPAND) return True
def icq_srv_07da_019a(o, uid, result, data): fmt = ''' length H uin I nick lnts first lnts last lnts _ lnts '''.split() names, types = fmt[::2],fmt[1::2] fmt = zip(names, types) __, _uin, nick, first, last, __ = oscar.unpack(fmt, data, '<') assert _uin == uid b = o.buddies[uid] try: personal = b.personal except Exception: personal = b.personal = util.Storage() for x in 'nick first last'.split(): setattr(personal, x, locals()[x])
def defaultprefs(): ''' Returns the default prefs as a Storage object ''' import prefs import stdpaths import config the_prefs = util.Storage() resdir = os.path.join(util.program_dir(), 'res') filenames = [ os.path.join(resdir, 'defaults.yaml'), os.path.join(resdir, config.platformName, 'defaults.yaml'), stdpaths.config / 'prefs.yaml', stdpaths.userdata / 'prefs.yaml', ] for filename in filenames: info('loading prefs from %r', filename) try: with open(filename, 'rb') as f: prefdict = syck.load(f) except Exception, e: log.info('Error loading prefs from %r: %r', filename, e) continue if not isinstance(prefdict, dict): continue if not sys.DEV: prefdict.pop('debug', None) prefdict = prefs.flatten(prefdict) the_prefs.update(prefdict)
def handle_success_loginpage(self, _name, resp): doc = resp.document if doc is None: raise NotInbox() if int(self.PP_AUTH_VERSION) < 900: form = None for form in doc.forms: if form.get( 'name' ) == 'f1': # it would be great if this had a real name, like "login" or something. break if form is None: self.handle_error(_name, Exception('No login form found')) log.error("Document: %r", HTML.tostring(doc)) return form.fields['login'] = self.username form.fields['passwd'] = self._decryptedpw() self._login_form = form else: data = HTML.tostring(doc) log.error("Document: %r", data) ppft_html = eval(util.get_between(data, "sFTTag:", ",") or 'None') ppft_token = HTML.fromstring(ppft_html).attrib['value'] bk = str(int(time.time())) action_url = net.UrlQuery( 'https://login.live.com/ppsecure/post.srf', **{ 'bk': bk, 'cbcxt': 'mai', 'ct': bk, 'id': '64855', 'lc': '1033', 'mkt': 'en-us', 'rpsnv': '11', 'rver': '6.1.6206.0', 'snsc': '1', 'wa': 'wsignin1.0', 'wp': 'MBI', 'wreply': 'https://mail.live.com/default.aspx' }) if _is_login_domain_exception(self.username): action_url = action_url.replace('login.live.com', 'msnia.login.live.com') self._login_form = util.Storage(form_values=lambda: dict( login=self.username, passwd=self._decryptedpw(), type='11', LoginOptions='2', NewUser='******', MEST='', PPSX='Passp', PPFT=ppft_token, idsbho='1', PwdPad='', sso='', i1='1', i2='1', i3='161605', i4='', i12='1', ), action=action_url) log.info('Got loginform for %r, submitting', self) self.request('sendauth')
def icq_srv_07da_00dc(o, uid, result, data): ''' WORD.L xx xx AGE The age of the user. 0 or -1 is invalid and means not entered. BYTE xx GENDER The gender of the user. LNTS xx .. HOMEPAGE The homepage of the user. WORD.L xx xx YEAR The year of birth of the user. BYTE xx MONTH The month of birth of the user. BYTE xx DAY The day of birth of the user. BYTE xx LANG1 The language the user speaks fluently. BYTE xx LANG2 Another language the user speaks. BYTE xx LANG3 Another language the user speaks. WORD.L xx xx UNKNOWN Unknown: Empty. LNTS xx .. OCITY city, the user is originally from LNTS xx .. OSTATE state, the user is originally from WORD.L xx xx OCOUNTRY The country the user originally is from. WORD.L xx xx MARITAL the user's marital status. ''' fmt = ''' age H gender B website lnts year H month B day B lang1 B lang2 B lang3 B unknown H hometown lnts homestate lnts homecountry H marital H '''.split() names, types = fmt[::2],fmt[1::2] fmt = zip(names, types) info = dict(zip(names+['data'], oscar.unpack(fmt, data,'<'))) b = o.buddies[uid] translate = dict( gender = {0: None, 1: _(u'Female'), 2: _(u'Male')}, ) #info['country'] = icq_country.codes[info['country']] try: personal = b.personal except Exception: personal = b.personal = util.Storage() from common import pref import time # format a birthday string if not all(info[c] == 0 for c in ('year', 'month', 'day')): try: personal['birthday'] = time.strftime(pref('infobox.birthday_format', '%m/%d/%y'), (info['year'], info['month'], info['day'], 0, 0, 0, 0, 0, 0)).decode('fuzzy utf8') except Exception, e: personal['birthday'] = u'' log.error("couldn't convert to string: %r, %r", e, info)
def digest(self, final=None): import struct return struct.pack('!Q', self.__val) def hexdigest(self, final=None): return util.to_hex(self.digest(final), '').lstrip('0') def fromfilename(self, fname): self.filename = fname self.__val = int(path.path(self.filename).size) HashLib = util.Storage( md5=hashlib.md5, sha1=hashlib.sha1, mtime=MTime, fsize=FSize, ) @util.memoize def _hashfile(pth, algs, mtime): hs = list(HashLib.get(alg)() for alg in algs) if any(needs_contents[x] for x in algs): with pth.open('rb') as f: bytes = f.read(4096) while bytes: for h in hs: h.update(bytes) bytes = f.read(4096)
except Exception, e: log.error('error decoding message: %r', e) traceback.print_exc() me, sender = str(uid), str(sender) try: assert me == o.username except Exception: print me, o.username for key in 'year month day hour minute mtype mflags mlength'.split(): print key, locals()[key] timestamp = datetime.datetime(year, month, day, hour, minute) oscar.snac.super_old_style_msg(o, util.Storage(name=sender), snd_uin=uid, msg=message, msg_type=mtype, timestamp=timestamp, offline=True) def icq_srv_0042(o, uid, data): assert len(data) == 1 and ord(data) == 0 o.send_snac(*ack_offline_msgs(o)) def icq_cli_07d0(o, data, uid): return x15_x02(o, 0x07d0, data, uid) #def icq_cli_07d0_0c3a(o, data, uid): # return x15_x02(o, 0x07d0, data, uid) # #def set_require_auth(o, require): # return icq_cli_07d0_0c3a(o, struct.pack('!10B', 0xf8, 0x02, 0x01, 0x00, # int(bool(require)), 0x0c, 0x03, 0x01, # 0x00, 0x00))
def testStorage(self): s = util.Storage({"key": "value"}) self.assertEquals(s.key, "value")