Example #1
0
 def OnShowMessage(self, evt):
     wx.MessageDialog(
         self.parent,
         StrConv(evt.message),
         StrConv(evt.title),
         wx.OK | evt.type
     ).ShowModal()
Example #2
0
    def ShowHeaders(self):
        '''
        Updates which headers and keys should be show and displays them.
        '''
        self.columns = COLUMN_INFO[self.type][0]
        self.keys = COLUMN_INFO[self.type][1]

        cnt = len(self.columns)

        for i in range(cnt):
            self.InsertColumn(i, self.columns[i])

        # resize columns to fit content

        # FIXME: this should be acquired better!
        spc = 10

        maxval = [0] * cnt
        for i in range(cnt):
            size = self.GetTextExtent(StrConv(self.columns[i]))[0]
            # 16 bellow is for sort arrrow
            if size + 16 > maxval[i]:
                maxval[i] = size + 16

        for current in self.values:
            for i in range(cnt):
                size = self.GetTextExtent(StrConv(current[self.keys[i]]))
                if size[0] > maxval[i]:
                    maxval[i] = size[0]
        for i in range(cnt - 1):
            self.SetColumnWidth(i, maxval[i] + spc)
        self.resizeLastColumn(maxval[cnt - 1] + spc)
Example #3
0
def GetTypeString(type, value, values, linkphone=True):
    '''
    Returns string for entry in data dictionary. Formats it according to
    knowledge of format types.
    '''
    t = GetItemType(type)
    if t == 'contact':
        i = SearchLocation(values['contact']['ME'], value)
        if i == -1:
            return '%d' % value
        else:
            return GetContactLink([] + values['contact']['ME'], i, str(value))
    elif linkphone and t == 'phone':
        return StrConv(
            GetNumberLink([] + values['contact']['ME'] +
                          values['contact']['SM'], value))
    elif t == 'id':
        v = hex(value)
        if v[-1] == 'L':
            v = v[:-1]
        return v
    elif t == 'photo':
        return '<wxp module="Wammu.Image" class="EncodedBitmap">' + \
                    '<param name="image" value="' + \
                    base64.b64encode(value) + \
                    '">' + \
                    '</wxp>'
    else:
        return StrConv(value)
Example #4
0
    def OnInit(self):

        self.SetAppName('Wammu Phone Configuration Wizard')
        vendor = StrConv(u'Michal Čihař')
        if vendor.find('?') != -1:
            vendor = 'Michal Čihař'
        self.SetVendorName(vendor)

        # Return a success flag
        return True
Example #5
0
def SelectContactNumber(parent, item):
    '''
    Selects number of chosen contact. If it has single number, it returns it
    directly, otherwise user has to select which number to use.
    '''
    numbers = []
    texts = []
    for i in range(len(item['Entries'])):
        if Wammu.Utils.GetItemType(item['Entries'][i]['Type']) == 'phone':
            numbers.append(item['Entries'][i]['Value'])
            texts.append(
                StrConv(
                    '%s : %s' %
                    (item['Entries'][i]['Type'], item['Entries'][i]['Value'])))

    if len(numbers) == 0:
        return None
    elif len(numbers) == 1:
        return numbers[0]
    dlg = wx.SingleChoiceDialog(parent,
                                _('Select number for selected contact'),
                                _('Select phone number'), texts,
                                wx.CHOICEDLG_STYLE | wx.RESIZE_BORDER)
    if dlg.ShowModal() == wx.ID_OK:
        result = numbers[dlg.GetSelection()]
    else:
        result = None
    del dlg
    return result
Example #6
0
    def run(self):
        try:
            self.listed_device_search()
            self.bluetooth_device_search()

            i = 0
            while len(self.threads) > 0:
                if self.threads[i].isAlive():
                    i += 1
                else:
                    if self.msgcallback is not None:
                        self.msgcallback(
                            _('Finished %s') %
                            StrConv(self.threads[i].getName()))
                    del self.threads[i]
                if i >= len(self.threads):
                    i = 0
            if self.msgcallback is not None:
                self.msgcallback(
                    _('All finished, found %d phones') % len(self.list))
            if self.callback is not None:
                self.callback(self.list)
        except:
            evt = Wammu.Events.ExceptionEvent(data=sys.exc_info())
            wx.PostEvent(self.win, evt)
Example #7
0
    def bluetooth_device_search_bluez(self):
        '''
        Initiates searching for Bluetooth devices using PyBluez stack.
        '''
        # read devices list
        if self.msgcallback is not None:
            self.msgcallback(
                _('Discovering Bluetooth devices using %s') % 'PyBluez')

        try:
            discovery = Wammu.BluezDiscovery.Discovery(self)
            discovery.find_devices()
            discovery.process_inquiry()
            if len(discovery.names_found
                   ) == 0 and self.msgcallback is not None:
                self.msgcallback(_('No Bluetooth device found'))
            if self.msgcallback is not None:
                self.msgcallback(
                    _('All Bluetooth devices discovered, connection tests still in progress…'
                      ))
        except bluetooth.BluetoothError as txt:
            if self.msgcallback is not None:
                self.msgcallback(
                    _('Could not access Bluetooth subsystem (%s)') %
                    StrConv(txt))
Example #8
0
 def OnGetItemText(self, item, col):
     '''
     Get item text.
     '''
     if item >= len(self.values):
         return None
     return StrConv(self.values[item][self.keys[col]])
Example #9
0
def ParseMessage(msg, parseinfo=False):
    txt = ''
    loc = ''
    msg['Folder'] = msg['SMS'][0]['Folder']
    msg['State'] = msg['SMS'][0]['State']
    msg['Number'] = msg['SMS'][0]['Number']
    msg['Name'] = msg['SMS'][0]['Name']
    msg['DateTime'] = msg['SMS'][0]['DateTime']
    if parseinfo:
        for i in msg['SMSInfo']['Entries']:
            if i['Buffer'] is not None:
                txt = txt + i['Buffer']
    else:
        for i in msg['SMS']:
            txt = txt + i['Text']
    for i in msg['SMS']:
        if loc != '':
            loc = loc + ', '
        loc = loc + str(i['Location'])
    try:
        StrConv(txt)
        msg['Text'] = txt
    except:
        s2 = ''
        for x in txt:
            if x in string.printable:
                s2 += x
        msg['Text'] = s2
    msg['Location'] = loc
    msg['Synced'] = False
    return msg
Example #10
0
    def __init_data(self):
        self.numberlist = []
        self.optionslist = []

        for item in self.contacts:
            numbers = []
            texts = []
            prefix = ''
            if item['Name'] != '':
                prefix = '%s: ' % item['Name']
            for i in range(len(item['Entries'])):
                if Wammu.Utils.GetItemType(item['Entries'][i]['Type']) == 'phone':
                    numbers.append(item['Entries'][i]['Value'])
                    texts.append(StrConv('%s (%s)' % (item['Entries'][i]['Value'], item['Entries'][i]['Type'])))

            if len(numbers) == 0:
                continue

            for x in range(len(numbers)):
                self.numberlist.append(numbers[x])
                self.optionslist.append(prefix + texts[x])

        self.currentlist = Wammu.PhoneValidator.SplitNumbers(self.current)
        self.wildcard = ''
        self.wildcard += _('Contact list') + ' (*.contactlist)|*.contactlist|'
        self.wildcard += _('All files') + ' (*.*)|*.*'
Example #11
0
def FormatError(txt, info, gammu_config = None):
    if info['Code'] == gammu.Errors['ERR_NOTSUPPORTED']:
        message = _('Your phone doesn\'t support this function.')
    elif info['Code'] == gammu.Errors['ERR_NOTIMPLEMENTED']:
        message = _('This function is not implemented for your phone. If you want help with implementation please contact authors.')
    elif info['Code'] == gammu.Errors['ERR_SECURITYERROR']:
        message = _('Your phone asks for PIN.')
    elif info['Code'] == gammu.Errors['ERR_FULL']:
        message = _('Memory is full, try deleting some entries.')
    elif info['Code'] == gammu.Errors['ERR_CANCELED']:
        message = _('Communication canceled by phone, did you press cancel on phone?')
    elif info['Code'] == gammu.Errors['ERR_EMPTY']:
        message = _('Empty entry received. This usually should not happen and most likely is caused by bug in phone firmware or in Gammu/Wammu.\n\nIf you miss some entry, please contact Gammu/Wammu authors.')
    elif info['Code'] == gammu.Errors['ERR_INSIDEPHONEMENU']:
        message = _('Please close opened menu in phone and retry, data can not be accessed while you have opened them.')
    elif info['Code'] == gammu.Errors['ERR_TIMEOUT']:
        message = _('Timeout while trying to communicate with phone. Maybe phone is not connected (for cable) or out of range (for Bluetooth or IrDA).')
    elif info['Code'] == gammu.Errors['ERR_DEVICENOTEXIST']:
        if gammu_config is None:
            message = _('Device for communication with phone does not exist. Maybe you don\'t have phone plugged or your configuration is wrong.')
        else:
            message = _('Device "%s" for communication with phone does not exist. Maybe you don\'t have phone plugged or your configuration is wrong.') % gammu_config['Device']
    elif info['Code'] == gammu.Errors['ERR_DEVICENOPERMISSION']:
        if sys.platform[:5] == 'linux':
            message_group = ' ' + _('Maybe you need to be member of some group to have acces to device.')
        else:
            message_group = ''
        if gammu_config is None:
            message = _('Can not access device for communication with phone.')
        else:
            check = CheckDeviceNode(gammu_config['Device'])
            if check[0] == -2:
                message = check[3]
                message_group = ''
            else:
                message = _('Can not access device "%s" for communication with phone.') % gammu_config['Device']
        if message_group != '':
            message += ' ' + message_group
    elif info['Code'] == gammu.Errors['ERR_NOSIM']:
        message = _('Can not access SIM card. Please check whether it is properly inserted in phone and/or try to reboot the phone by removing battery.')
    else:
        message = '%s %s\n%s %s\n%s %d' % (_('Description:'), StrConv(info['Text']), _('Function:'), info['Where'], _('Error code:'), info['Code'])
    return StrConv(txt + '\n\n' + message)
Example #12
0
    def OnInit(self):
        '''
        wxWindows call this method to initialize the application.
        '''

        self.SetAppName('Wammu')
        vendor = StrConv(u'Michal Čihař')
        if vendor.find('?') != -1:
            vendor = 'Michal Čihař'
        self.SetVendorName(vendor)

        frame = Wammu.Main.WammuFrame(None, -1)
        Wammu.Error.HANDLER_PARENT = frame

        frame.Show(True)
        frame.PostInit(self)
        self.SetTopWindow(frame)

        # Return a success flag
        return True
Example #13
0
    def OnInit(self):
        '''
        wxWindows call this method to initialize the application.
        '''

        self.SetAppName('Wammu')
        vendor = StrConv(u'Michal Čihař')
        if vendor.find('?') != -1:
            vendor = 'Michal Čihař'
        self.SetVendorName(vendor)

        frame = Wammu.Main.WammuFrame(None, -1)
        Wammu.Error.HANDLER_PARENT = frame

        frame.Show(True)
        frame.PostInit(self)
        self.SetTopWindow(frame)

        # Return a success flag
        return True
Example #14
0
 def create_search_thread(self, device, connections, name):
     '''
     Creates single thread for searching phone on device using listed
     connections. Name is just text which will be shown to user.
     '''
     newthread = SearchThread(device, connections, self.list, self.listlock,
                              self.lock, self.level)
     newthread.setName(name)
     if self.msgcallback is not None:
         self.msgcallback(_('Checking %s') % StrConv(name))
     self.threads.append(newthread)
     newthread.start()
Example #15
0
def SelectContact(parent, contactlist, index=False):
    '''
    Dialog for selecting contact.
    '''
    contactlist.sort(SortName)
    choices = []
    for entry in contactlist:
        if entry['Name'] == '':
            choices.append(StrConv(entry['Number']))
        else:
            choices.append(StrConv(entry['Name']))

    dlg = wx.SingleChoiceDialog(parent, _('Select contact from below list'),
                                _('Select contact'), choices,
                                wx.CHOICEDLG_STYLE | wx.RESIZE_BORDER)
    if dlg.ShowModal() == wx.ID_OK and len(choices) > 0:
        result = dlg.GetSelection()
        if not index:
            result = contactlist[result]['Location']
    else:
        result = -1
    del dlg
    return result
Example #16
0
    def SetContent(self, text):
        # default system colours
        bgc = wx.SystemSettings.GetColour(wx.SYS_COLOUR_LISTBOX)
        fgc = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)
        hfgc = wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)

        colours = 'text="#%02x%02x%02x" bgcolor="#%02x%02x%02x" link="#%02x%02x%02x"' % (
            fgc.Red(), fgc.Green(), fgc.Blue(), bgc.Red(), bgc.Green(),
            bgc.Blue(), hfgc.Red(), hfgc.Green(), hfgc.Blue())

        pagefmt = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=%s"></head><body %s>%s</body></html>'

        charset = 'ucs-2'
        text = StrConv(text)
        self.SetPage(pagefmt % (charset, colours, text))
Example #17
0
def Handler(errtype, value, tback):
    """User friendly error handling """

    # prepare traceback text
    trace = traceback.extract_tb(tback)
    linetrace = traceback.format_list(trace)
    texttrace = ''.join(linetrace)
    textexc = ''.join(traceback.format_exception_only(errtype, value))

    # debug log information
    logtext = ''
    outf, logname = Wammu.ErrorLog.SaveLog()
    if outf is not None:
        print 'Created debug log copy in %s for error reporting.' % logname
        logtext = '\n%s\n' % _(
            'Debug log was saved for phone communication, if this error appeared during communicating with phone, you are strongly encouraged to include it in bugreport. Debug log is saved in file %s.'
        ) % logname

    # detection of same errors
    tracehash = md5('%s,%s' % (textexc, texttrace)).hexdigest()
    if tracehash in ERROR_HISTORY:
        print 'Same error already detected, not showing dialog!'
        print texttrace
        print 'Exception: %s' % textexc
        return
    ERROR_HISTORY.append(tracehash)

    # traceback id (md5 sum of last topmost traceback item inside Wammu - file(function):code)
    try:
        for trace_line in trace:
            if trace_line[0].rfind('Wammu') > -1:
                lasttrace = trace_line
        traceidtext = '%s(%s):%s' % (
            lasttrace[0][lasttrace[0].rfind('Wammu'):], lasttrace[2],
            lasttrace[3])
        traceid = md5(traceidtext).hexdigest()
        tracetext = '\n%s\n' % (
            _('Before submiting please try searching for simmilar bugs on %s')
            %
            ('https://github.com/search?l=&q=%s+%%40gammu&ref=advsearch&type=Issues'
             % traceid))
    except:
        traceid = 'N/A'
        tracetext = ''

    # unicode warning
    if errtype == UnicodeEncodeError or errtype == UnicodeDecodeError:
        unicodewarning = '\n%s\n' % (_(
            'Unicode encoding error appeared, see question 1 in FAQ, how to solve this.'
        ))
    else:
        unicodewarning = ''

    # prepare message
    text = u"""%s

%s
%s%s%s
%s
------------------ Traceback ID -------------------
%s
-------------------- Traceback --------------------
%s-------------------- Exception --------------------
%s---------------------------------------------------
""" % (_('Unhandled exception appeared.'),
       _('If you want to help improving this program, please submit following infomation and description how did it happen to %s. Please report in english, otherwise you will be most likely told to translate you report to english later.'
         ) % 'http://bugs.wammu.eu/', logtext, tracetext, unicodewarning,
       Wammu.ErrorLog.GetSystemInfo(), traceid, StrConv(texttrace),
       StrConv(textexc))

    # Include exception info in crash file
    if outf is not None:
        outf.write(text.encode('utf-8'))
        outf.close()

    # display error
    try:
        Wammu.ErrorMessage.ErrorMessage(
            HANDLER_PARENT,
            _('Unhandled exception appeared. If you want to help improving this program, please report this together with description how this situation has happened. Please report in english, otherwise you will be most likely told to translate you report to english later.'
              ),
            _('Unhandled exception'),
            traceid=traceid,
            autolog=logname,
            exception=_('Traceback:\n%(traceback)s\nException: %(exception)s')
            % {
                'traceback': StrConv(texttrace),
                'exception': StrConv(textexc)
            }).ShowModal()
    except:
        print text
Example #18
0
def GetNumberLink(lst, number):
    i = SearchNumber(lst, number)
    if i == -1:
        return StrConv(number)
    return GetContactLink(lst, i, number)
Example #19
0
 def OnText(self, evt):
     self.edit.AppendText(StrConv(evt.text))
Example #20
0
 def AddTypeEdit(self, row, value):
     type = Wammu.Utils.GetItemType(value['Type'])
     self.fulltypes[row] = value['Type']
     self.types[row] = type
     if type == 'text' or type == None:
         # text editor
         edit = wx.TextCtrl(self,
                            -1,
                            StrConv(value['Value']),
                            size=(200, -1))
         self.sizer.Add(edit, (row + self.rowoffset, 4), (1, 4))
         self.edits[row] = [edit]
     elif type == 'phone':
         # phone editor with voice tag
         edit = wx.TextCtrl(
             self,
             -1,
             StrConv(value['Value']),
             size=(150, -1),
             validator=Wammu.PhoneValidator.PhoneValidator(pause=True))
         self.sizer.Add(edit, (row + self.rowoffset, 4), (1, 3))
         try:
             v = hex(value['VoiceTag'])
         except:
             v = '0x0'
         if v[-1] == 'L':
             v = v[:-1]
         edit2 = wx.TextCtrl(self, -1, v, size=(50, -1))
         self.sizer.Add(edit2, (row + self.rowoffset, 7), (1, 1))
         self.edits[row] = [edit, edit2]
     elif type == 'bool':
         # boolean
         try:
             val = bool(value['Value'])
         except:
             val = False
         edit = wx.CheckBox(self, -1, '', size=(200, -1))
         edit.SetValue(val)
         self.sizer.Add(edit, (row + self.rowoffset, 4), (1, 4))
         self.edits[row] = [edit]
     elif type == 'contact':
         # contact editor
         try:
             val = int(value['Value'])
         except:
             val = 0
         edit = wx.SpinCtrl(self,
                            -1,
                            str(val),
                            style=wx.SP_WRAP | wx.SP_ARROW_KEYS,
                            min=0,
                            max=10000,
                            initial=val,
                            size=(50, -1))
         edit.row = row
         self.sizer.Add(edit, (row + self.rowoffset, 4), (1, 1))
         edit2 = wx.Button(self,
                           -1,
                           self.GetContactText(val),
                           style=wx.BU_EXACTFIT,
                           size=(150, -1))
         edit2.row = row
         self.sizer.Add(edit2, (row + self.rowoffset, 5), (1, 3))
         self.edits[row] = [edit, edit2]
         self.Bind(wx.EVT_SPINCTRL, self.OnContactSpinChange, edit)
         self.Bind(wx.EVT_BUTTON, self.OnContactButton, edit2)
     elif type == 'id':
         # ID editor
         try:
             v = hex(value['Value'])
         except:
             v = '0x0'
         if v[-1] == 'L':
             v = v[:-1]
         edit = wx.TextCtrl(self, -1, StrConv(v), size=(200, -1))
         self.sizer.Add(edit, (row + self.rowoffset, 4), (1, 4))
         self.edits[row] = [edit]
     elif type == 'category' or type == 'number':
         # number editor
         # FIXME: category should be selectable
         try:
             val = int(value['Value'])
         except:
             val = 0
         edit = wx.SpinCtrl(self,
                            -1,
                            str(val),
                            style=wx.SP_WRAP | wx.SP_ARROW_KEYS,
                            min=-10000,
                            max=10000,
                            initial=val,
                            size=(200, -1))
         self.sizer.Add(edit, (row + self.rowoffset, 4), (1, 4))
         self.edits[row] = [edit]
     elif type == 'datetime':
         # date + time editor
         edit = TimeCtrl(self, -1, fmt24hr=True)
         Wammu.Utils.FixupMaskedEdit(edit)
         edit.SetValue(TimeToText(value['Value'], self.cfg))
         self.sizer.Add(edit, (row + self.rowoffset, 4), (1, 2))
         edit2 = DateControl(self, DateToText(value['Value'], self.cfg))
         self.sizer.Add(edit2, (row + self.rowoffset, 6), (1, 2))
         self.edits[row] = [edit, edit2]
     elif type == 'date':
         # date editor
         edit = DateControl(self, DateToText(value['Value'], self.cfg))
         self.sizer.Add(edit, (row + self.rowoffset, 4), (1, 4))
         self.edits[row] = [edit]
     else:
         print 'warning: creating TextCtrl for %s' % type
         edit = wx.TextCtrl(self,
                            -1,
                            StrConv(value['Value']),
                            size=(200, -1))
         self.sizer.Add(edit, (row + self.rowoffset, 4), (1, 4))
         self.edits[row] = [edit]
     self.sizer.Fit(self)
     self.sizer.SetSizeHints(self)
     self.sizer.Layout()
Example #21
0
    def Okay(self, evt):
        connection = self.connection_combo_box.GetValue()
        if connection == self.ns_string:
            connection = 'NULL'
        if len(self.features) == 0 and connection != 'NULL':
            wx.MessageDialog(
                self,
                _('Entry in Gammu Phone Database was not created, following fields are invalid:\n%s') % _('Supported features'),
                _('Entry not created!'),
                wx.OK | wx.ICON_ERROR
            ).ShowModal()
            return
        elif len(self.features) != 0 and connection == 'NULL':
            wx.MessageDialog(
                self,
                _('Entry in Gammu Phone Database was not created, following fields are invalid:\n%s') % _('Supported features'),
                _('Entry not created!'),
                wx.OK | wx.ICON_ERROR
            ).ShowModal()
            return
        man_str = self.manufacturer_choice.GetStringSelection()
        try:
            man_id = Wammu.Data.ManufacturerMap[man_str]
        except:
            wx.MessageDialog(
                self,
                _('Entry in Gammu Phone Database was not created, following fields are invalid:\n%s') % _('Manufacturer'),
                _('Entry not created!'),
                wx.OK | wx.ICON_ERROR
            ).ShowModal()
            return
        garble_id = self.mangle_choice.GetSelection()
        try:
            garble_text = Wammu.Data.GarbleMap[garble_id]
        except:
            wx.MessageDialog(
                self,
                _('Entry in Gammu Phone Database was not created, following fields are invalid:\n%s') % _('Email displaying'),
                _('Entry not created!'),
                wx.OK | wx.ICON_ERROR
            ).ShowModal()
            return

        # Remember user information for next run
        self.wammu_cfg.Write('/User/Name', self.name_text_ctrl.GetValue())
        self.wammu_cfg.Write('/User/Email', self.email_text_ctrl.GetValue())

        # Prepare data to post
        params_dict = {
            'irobot': 'wammu',
            'version': '2',
            'manufacturer': man_id,
            'name': self.model_text_ctrl.GetValue(),
            'model': self.model_combo_box.GetValue(),
            'connection': connection,
            'note': self.note_text_ctrl.GetValue(),
            'author_name': self.name_text_ctrl.GetValue(),
            'author_email': self.email_text_ctrl.GetValue(),
            'email_garble': garble_text,
            'gammu_version': gammu.Version()[0],
        }
        for x in self.features:
            params_dict['fts[%s]' % x] = 1

        # Convert unicode to raw utf-8 strigns so that they can be properly
        # handled by urllib and later by website
        for x in params_dict.keys():
            if type(params_dict[x]) == unicode:
                params_dict[x] = params_dict[x].encode('utf-8')

        # Encode request and prepare headers
        params = urllib.urlencode(params_dict)
        headers = {
            'Content-type': 'application/x-www-form-urlencoded',
            'Accept': 'text/plain'
        }

        # Perform request
        conn = httplib.HTTPConnection('wammu.eu')
        try:
            conn.request('POST', '/api/phones/new/', params, headers)

            # Check request response
            response = conn.getresponse()
            if response.status != 200:
                wx.MessageDialog(
                    self,
                    _('HTTP request failed with status %(code)d (%(text)s), please retry later or create entry manually.') % {
                        'code': response.status,
                        'text': response.reason,
                    },
                    _('Entry not created!'),
                    wx.OK | wx.ICON_ERROR
                ).ShowModal()
                return
        except Exception as e:
            if hasattr(e, 'message') and e.message != '':
                msg = e.message
            elif hasattr(e, 'args') and len(e.args) > 0:
                msg = e.args[-1]
            else:
                msg = str(e)
            wx.MessageDialog(
                self,
                _('HTTP request failed with exception:\n%(exception)s\nPlease retry later or create entry manually.') % {
                    'exception': StrConv(msg),
                },
                _('Entry not created!'),
                wx.OK | wx.ICON_ERROR
            ).ShowModal()
            return

        # Verify acquired data
        data = response.read()
        conn.close()
        ok_test = OK_MATCHER.match(data)
        if ok_test is not None:
            url = 'https://%swammu.eu%s' % (Wammu.Utils.GetWebsiteLang(), ok_test.groups()[1])
            result = wx.MessageDialog(
                self,
                _('Entry in Gammu Phone Database has been created, you can see it on <%s> URL.\nDo you want to open it in browser now?') % url,
                _('Entry created!'),
                wx.YES_NO | wx.ICON_INFORMATION
            ).ShowModal()
            if result == wx.ID_YES:
                Wammu.Webbrowser.Open(url)
            self.wammu_cfg.Write('/Wammu/TalkbackDone', 'yes')

            self.EndModal(wx.ID_OK)

        fail_test = FAIL_MATCHER.match(data)
        if fail_test is not None:
            wrong_fields = fail_test.groups()[0].split(',')
            fields_msg = ''
            for field in wrong_fields:
                if field == 'manufacturer':
                    fields_msg += _('Manufacturer') + '\n'
                elif field == 'name':
                    fields_msg += _('Phone model') + '\n'
                elif field == 'model':
                    fields_msg += _('Model in gammu configuration') + '\n'
                elif field == 'connection':
                    fields_msg += _('Connection type') + '\n'
                elif field == 'note':
                    fields_msg += _('Note') + '\n'
                elif field == 'author_name':
                    fields_msg += _('Your name') + '\n'
                elif field == 'author_email':
                    fields_msg += _('Your email') + '\n'
                elif field == 'email_garble':
                    fields_msg += _('Email displaying') + '\n'
                elif field == 'gammu_version':
                    fields_msg += _('Gammu version') + '\n'
                else:
                    fields_msg += _('Field: %s') % field + '\n'

            wx.MessageDialog(
                self,
                _('Entry in Gammu Phone Database was not created, following fields are invalid:\n%s') % fields_msg,
                _('Entry not created!'),
                wx.OK | wx.ICON_ERROR
            ).ShowModal()
            return
Example #22
0
    def Okay(self, evt):
        connection = self.connection_combo_box.GetValue()
        if connection == self.ns_string:
            connection = 'NULL'
        if len(self.features) == 0 and connection != 'NULL':
            wx.MessageDialog(self,
                _('Entry in Gammu Phone Database was not created, following fields are invalid:\n%s') % _('Supported features'),
                _('Entry not created!'),
                wx.OK | wx.ICON_ERROR).ShowModal()
            return
        elif len(self.features) != 0 and connection == 'NULL':
            wx.MessageDialog(self,
                _('Entry in Gammu Phone Database was not created, following fields are invalid:\n%s') % _('Supported features'),
                _('Entry not created!'),
                wx.OK | wx.ICON_ERROR).ShowModal()
            return
        man_str = self.manufacturer_choice.GetStringSelection()
        try:
            man_id = Wammu.Data.ManufacturerMap[man_str]
        except:
            wx.MessageDialog(self,
                _('Entry in Gammu Phone Database was not created, following fields are invalid:\n%s') % _('Manufacturer'),
                _('Entry not created!'),
                wx.OK | wx.ICON_ERROR).ShowModal()
            return
        garble_id = self.mangle_choice.GetSelection()
        try:
            garble_text = Wammu.Data.GarbleMap[garble_id]
        except:
            wx.MessageDialog(self,
                _('Entry in Gammu Phone Database was not created, following fields are invalid:\n%s') % _('Email displaying'),
                _('Entry not created!'),
                wx.OK | wx.ICON_ERROR).ShowModal()
            return

        # Remember user information for next run
        self.wammu_cfg.Write('/User/Name', self.name_text_ctrl.GetValue())
        self.wammu_cfg.Write('/User/Email', self.email_text_ctrl.GetValue())

        # Prepare data to post
        params_dict = {
            'irobot': 'wammu',
            'version': '2',
            'manufacturer': man_id,
            'name': self.model_text_ctrl.GetValue(),
            'model': self.model_combo_box.GetValue(),
            'connection': connection,
            'note': self.note_text_ctrl.GetValue(),
            'author_name': self.name_text_ctrl.GetValue(),
            'author_email': self.email_text_ctrl.GetValue(),
            'email_garble': garble_text,
            'gammu_version': gammu.Version()[0],
        }
        for x in self.features:
            params_dict['fts[%s]' % x] = 1

        # Convert unicode to raw utf-8 strigns so that they can be properly
        # handled by urllib and later by website
        for x in params_dict.keys():
            if type(params_dict[x]) == unicode:
                params_dict[x] = params_dict[x].encode('utf-8')

        # Encode request and prepare headers
        params = urllib.urlencode(params_dict)
        headers = {'Content-type': 'application/x-www-form-urlencoded',
                    'Accept': 'text/plain'}

        # Perform request
        conn = httplib.HTTPConnection('wammu.eu')
        try:
            conn.request('POST', '/api/phones/new/', params, headers)

            # Check request response
            response = conn.getresponse()
            if response.status != 200:
                wx.MessageDialog(self,
                    _('HTTP request failed with status %(code)d (%(text)s), please retry later or create entry manually.') % {
                        'code': response.status,
                        'text': response.reason,
                        },
                    _('Entry not created!'),
                    wx.OK | wx.ICON_ERROR).ShowModal()
                return
        except Exception, e:
            if hasattr(e, 'message') and e.message != '':
                msg = e.message
            elif hasattr(e, 'args') and len(e.args) > 0:
                msg = e.args[-1]
            else:
                msg = str(e)
            wx.MessageDialog(self,
                _('HTTP request failed with exception:\n%(exception)s\nPlease retry later or create entry manually.') % {
                    'exception': StrConv(msg),
                    },
                _('Entry not created!'),
                wx.OK | wx.ICON_ERROR).ShowModal()
            return
Example #23
0
def GetContactLink(lst, i, txt):
    return StrConv(
        '<a href="memory://%s/%d">%s</a> (%s)' %
        (lst[i]['MemoryType'], lst[i]['Location'], lst[i]['Name'], txt))